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