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