001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.io.input.buffer;
018
019import static org.apache.commons.io.IOUtils.EOF;
020
021import java.io.FilterInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024import java.util.Objects;
025
026import org.apache.commons.io.IOUtils;
027
028/**
029 * Implements a buffered input stream, which is internally based on a {@link CircularByteBuffer}. Unlike the
030 * {@link java.io.BufferedInputStream}, this one doesn't need to reallocate byte arrays internally.
031 */
032public class CircularBufferInputStream extends FilterInputStream {
033
034    /** Internal buffer. */
035    protected final CircularByteBuffer buffer;
036
037    /** Internal buffer size. */
038    protected final int bufferSize;
039
040    /** Whether we've seen the input stream EOF. */
041    private boolean eof;
042
043    /**
044     * Constructs a new instance, which filters the given input stream, and uses a reasonable default buffer size
045     * ({@link IOUtils#DEFAULT_BUFFER_SIZE}).
046     *
047     * @param inputStream The input stream, which is being buffered.
048     */
049    public CircularBufferInputStream(final InputStream inputStream) {
050        this(inputStream, IOUtils.DEFAULT_BUFFER_SIZE);
051    }
052
053    /**
054     * Constructs a new instance, which filters the given input stream, and uses the given buffer size.
055     *
056     * @param inputStream The input stream, which is being buffered.
057     * @param bufferSize The size of the {@link CircularByteBuffer}, which is used internally.
058     */
059    @SuppressWarnings("resource") // Caller closes InputStream
060    public CircularBufferInputStream(final InputStream inputStream, final int bufferSize) {
061        super(Objects.requireNonNull(inputStream, "inputStream"));
062        if (bufferSize <= 0) {
063            throw new IllegalArgumentException("Illegal bufferSize: " + bufferSize);
064        }
065        this.buffer = new CircularByteBuffer(bufferSize);
066        this.bufferSize = bufferSize;
067        this.eof = false;
068    }
069
070    @Override
071    public void close() throws IOException {
072        super.close();
073        eof = true;
074        buffer.clear();
075    }
076
077    /**
078     * Fills the buffer with the contents of the input stream.
079     *
080     * @throws IOException in case of an error while reading from the input stream.
081     */
082    protected void fillBuffer() throws IOException {
083        if (eof) {
084            return;
085        }
086        int space = buffer.getSpace();
087        final byte[] buf = IOUtils.byteArray(space);
088        while (space > 0) {
089            final int res = in.read(buf, 0, space);
090            if (res == EOF) {
091                eof = true;
092                return;
093            }
094            if (res > 0) {
095                buffer.add(buf, 0, res);
096                space -= res;
097            }
098        }
099    }
100
101    /**
102     * Fills the buffer from the input stream until the given number of bytes have been added to the buffer.
103     *
104     * @param count number of byte to fill into the buffer
105     * @return true if the buffer has bytes
106     * @throws IOException in case of an error while reading from the input stream.
107     */
108    protected boolean haveBytes(final int count) throws IOException {
109        if (buffer.getCurrentNumberOfBytes() < count) {
110            fillBuffer();
111        }
112        return buffer.hasBytes();
113    }
114
115    @Override
116    public int read() throws IOException {
117        if (!haveBytes(1)) {
118            return EOF;
119        }
120        return buffer.read() & 0xFF; // return unsigned byte
121    }
122
123    @Override
124    public int read(final byte[] targetBuffer, final int offset, final int length) throws IOException {
125        Objects.requireNonNull(targetBuffer, "targetBuffer");
126        if (offset < 0) {
127            throw new IllegalArgumentException("Offset must not be negative");
128        }
129        if (length < 0) {
130            throw new IllegalArgumentException("Length must not be negative");
131        }
132        if (!haveBytes(length)) {
133            return EOF;
134        }
135        final int result = Math.min(length, buffer.getCurrentNumberOfBytes());
136        for (int i = 0; i < result; i++) {
137            targetBuffer[offset + i] = buffer.read();
138        }
139        return result;
140    }
141}