CircularBufferInputStream.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.io.input.buffer;

  18. import static org.apache.commons.io.IOUtils.EOF;

  19. import java.io.BufferedInputStream;
  20. import java.io.FilterInputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.util.Objects;

  24. import org.apache.commons.io.IOUtils;

  25. /**
  26.  * Implements a buffered input stream, which is internally based on a {@link CircularByteBuffer}. Unlike the
  27.  * {@link BufferedInputStream}, this one doesn't need to reallocate byte arrays internally.
  28.  *
  29.  * @since 2.7
  30.  */
  31. public class CircularBufferInputStream extends FilterInputStream {

  32.     /** Internal buffer. */
  33.     protected final CircularByteBuffer buffer;

  34.     /** Internal buffer size. */
  35.     protected final int bufferSize;

  36.     /** Whether we've seen the input stream EOF. */
  37.     private boolean eof;

  38.     /**
  39.      * Constructs a new instance, which filters the given input stream, and uses a reasonable default buffer size
  40.      * ({@link IOUtils#DEFAULT_BUFFER_SIZE}).
  41.      *
  42.      * @param inputStream The input stream, which is being buffered.
  43.      */
  44.     public CircularBufferInputStream(final InputStream inputStream) {
  45.         this(inputStream, IOUtils.DEFAULT_BUFFER_SIZE);
  46.     }

  47.     /**
  48.      * Constructs a new instance, which filters the given input stream, and uses the given buffer size.
  49.      *
  50.      * @param inputStream The input stream, which is being buffered.
  51.      * @param bufferSize The size of the {@link CircularByteBuffer}, which is used internally.
  52.      */
  53.     @SuppressWarnings("resource") // Caller closes InputStream
  54.     public CircularBufferInputStream(final InputStream inputStream, final int bufferSize) {
  55.         super(Objects.requireNonNull(inputStream, "inputStream"));
  56.         if (bufferSize <= 0) {
  57.             throw new IllegalArgumentException("Illegal bufferSize: " + bufferSize);
  58.         }
  59.         this.buffer = new CircularByteBuffer(bufferSize);
  60.         this.bufferSize = bufferSize;
  61.         this.eof = false;
  62.     }

  63.     @Override
  64.     public void close() throws IOException {
  65.         super.close();
  66.         eof = true;
  67.         buffer.clear();
  68.     }

  69.     /**
  70.      * Fills the buffer with the contents of the input stream.
  71.      *
  72.      * @throws IOException in case of an error while reading from the input stream.
  73.      */
  74.     protected void fillBuffer() throws IOException {
  75.         if (eof) {
  76.             return;
  77.         }
  78.         int space = buffer.getSpace();
  79.         final byte[] buf = IOUtils.byteArray(space);
  80.         while (space > 0) {
  81.             final int res = in.read(buf, 0, space);
  82.             if (res == EOF) {
  83.                 eof = true;
  84.                 return;
  85.             }
  86.             if (res > 0) {
  87.                 buffer.add(buf, 0, res);
  88.                 space -= res;
  89.             }
  90.         }
  91.     }

  92.     /**
  93.      * Fills the buffer from the input stream until the given number of bytes have been added to the buffer.
  94.      *
  95.      * @param count number of byte to fill into the buffer
  96.      * @return true if the buffer has bytes
  97.      * @throws IOException in case of an error while reading from the input stream.
  98.      */
  99.     protected boolean haveBytes(final int count) throws IOException {
  100.         if (buffer.getCurrentNumberOfBytes() < count) {
  101.             fillBuffer();
  102.         }
  103.         return buffer.hasBytes();
  104.     }

  105.     @Override
  106.     public int read() throws IOException {
  107.         if (!haveBytes(1)) {
  108.             return EOF;
  109.         }
  110.         return buffer.read() & 0xFF; // return unsigned byte
  111.     }

  112.     @Override
  113.     public int read(final byte[] targetBuffer, final int offset, final int length) throws IOException {
  114.         Objects.requireNonNull(targetBuffer, "targetBuffer");
  115.         if (offset < 0) {
  116.             throw new IllegalArgumentException("Offset must not be negative");
  117.         }
  118.         if (length < 0) {
  119.             throw new IllegalArgumentException("Length must not be negative");
  120.         }
  121.         if (!haveBytes(length)) {
  122.             return EOF;
  123.         }
  124.         final int result = Math.min(length, buffer.getCurrentNumberOfBytes());
  125.         for (int i = 0; i < result; i++) {
  126.             targetBuffer[offset + i] = buffer.read();
  127.         }
  128.         return result;
  129.     }
  130. }