    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.IOException;
    022import java.io.InputStream;
    023import java.util.Objects;
    024
    025import org.apache.commons.io.IOUtils;
    026
    027/**
    028 * Implements a buffered input stream, which is internally based on a {@link CircularByteBuffer}. Unlike the
    029 * {@link java.io.BufferedInputStream}, this one doesn't need to reallocate byte arrays internally.
    030 */
    031public class CircularBufferInputStream extends InputStream {
    032
    033    /** What we are streaming, used to fill the internal buffer. */
    034    protected final InputStream in;
    035
    036    /** Internal buffer. */
    037    protected final CircularByteBuffer buffer;
    038
    039    /** Internal buffer size. */
    040    protected final int bufferSize;
    041
    042    /** Whether we've see the input stream EOF. */
    043    private boolean eof;
    044
    045    /**
    046     * Creates a new instance, which filters the given input stream, and uses the given buffer size.
    047     *
    048     * @param inputStream The input stream, which is being buffered.
    049     * @param bufferSize The size of the {@link CircularByteBuffer}, which is used internally.
    050     */
    051    public CircularBufferInputStream(final InputStream inputStream, final int bufferSize) {
    052        if (bufferSize <= 0) {
    053            throw new IllegalArgumentException("Invalid bufferSize: " + bufferSize);
    054        }
    055        this.in = Objects.requireNonNull(inputStream, "inputStream");
    056        this.buffer = new CircularByteBuffer(bufferSize);
    057        this.bufferSize = bufferSize;
    058        this.eof = false;
    059    }
    060
    061    /**
    062     * Creates a new instance, which filters the given input stream, and uses a reasonable default buffer size
    063     * ({@link IOUtils#DEFAULT_BUFFER_SIZE}).
    064     *
    065     * @param inputStream The input stream, which is being buffered.
    066     */
    067    public CircularBufferInputStream(final InputStream inputStream) {
    068        this(inputStream, IOUtils.DEFAULT_BUFFER_SIZE);
    069    }
    070
    071    /**
    072     * Fills the buffer with the contents of the input stream.
    073     *
    074     * @throws IOException in case of an error while reading from the input stream.
    075     */
    076    protected void fillBuffer() throws IOException {
    077        if (eof) {
    078            return;
    079        }
    080        int space = buffer.getSpace();
    081        final byte[] buf = IOUtils.byteArray(space);
    082        while (space > 0) {
    083            final int res = in.read(buf, 0, space);
    084            if (res == EOF) {
    085                eof = true;
    086                return;
    087            }
    088            if (res > 0) {
    089                buffer.add(buf, 0, res);
    090                space -= res;
    091            }
    092        }
    093    }
    094
    095    /**
    096     * Fills the buffer from the input stream until the given number of bytes have been added to the buffer.
    097     *
    098     * @param count number of byte to fill into the buffer
    099     * @return true if the buffer has bytes
    100     * @throws IOException in case of an error while reading from the input stream.
    101     */
    102    protected boolean haveBytes(final int count) throws IOException {
    103        if (buffer.getCurrentNumberOfBytes() < count) {
    104            fillBuffer();
    105        }
    106        return buffer.hasBytes();
    107    }
    108
    109    @Override
    110    public int read() throws IOException {
    111        if (!haveBytes(1)) {
    112            return EOF;
    113        }
    114        return buffer.read() & 0xFF; // return unsigned byte
    115    }
    116
    117    @Override
    118    public int read(final byte[] buffer) throws IOException {
    119        return read(buffer, 0, buffer.length);
    120    }
    121
    122    @Override
    123    public int read(final byte[] targetBuffer, final int offset, final int length) throws IOException {
    124        Objects.requireNonNull(targetBuffer, "targetBuffer");
    125        if (offset < 0) {
    126            throw new IllegalArgumentException("Offset must not be negative");
    127        }
    128        if (length < 0) {
    129            throw new IllegalArgumentException("Length must not be negative");
    130        }
    131        if (!haveBytes(length)) {
    132            return EOF;
    133        }
    134        final int result = Math.min(length, buffer.getCurrentNumberOfBytes());
    135        for (int i = 0; i < result; i++) {
    136            targetBuffer[offset + i] = buffer.read();
    137        }
    138        return result;
    139    }
    140
    141    @Override
    142    public void close() throws IOException {
    143        in.close();
    144        eof = true;
    145        buffer.clear();
    146    }
    147}