View Javadoc
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  
19  import static org.apache.commons.io.IOUtils.EOF;
20  
21  import java.io.BufferedInputStream;
22  import java.io.FilterInputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.util.Objects;
26  
27  import org.apache.commons.io.IOUtils;
28  
29  /**
30   * Implements a buffered input stream, which is internally based on a {@link CircularByteBuffer}. Unlike the
31   * {@link BufferedInputStream}, this one doesn't need to reallocate byte arrays internally.
32   *
33   * @since 2.7
34   */
35  public class CircularBufferInputStream extends FilterInputStream {
36  
37      /** Internal buffer. */
38      protected final CircularByteBuffer buffer;
39  
40      /** Internal buffer size. */
41      protected final int bufferSize;
42  
43      /** Whether we've seen the input stream EOF. */
44      private boolean eof;
45  
46      /**
47       * Constructs a new instance, which filters the given input stream, and uses a reasonable default buffer size
48       * ({@link IOUtils#DEFAULT_BUFFER_SIZE}).
49       *
50       * @param inputStream The input stream, which is being buffered.
51       */
52      public CircularBufferInputStream(final InputStream inputStream) {
53          this(inputStream, IOUtils.DEFAULT_BUFFER_SIZE);
54      }
55  
56      /**
57       * Constructs a new instance, which filters the given input stream, and uses the given buffer size.
58       *
59       * @param inputStream The input stream, which is being buffered.
60       * @param bufferSize The size of the {@link CircularByteBuffer}, which is used internally.
61       */
62      @SuppressWarnings("resource") // Caller closes InputStream
63      public CircularBufferInputStream(final InputStream inputStream, final int bufferSize) {
64          super(Objects.requireNonNull(inputStream, "inputStream"));
65          if (bufferSize <= 0) {
66              throw new IllegalArgumentException("Illegal bufferSize: " + bufferSize);
67          }
68          this.buffer = new CircularByteBuffer(bufferSize);
69          this.bufferSize = bufferSize;
70          this.eof = false;
71      }
72  
73      @Override
74      public void close() throws IOException {
75          super.close();
76          eof = true;
77          buffer.clear();
78      }
79  
80      /**
81       * Fills the buffer with the contents of the input stream.
82       *
83       * @throws IOException in case of an error while reading from the input stream.
84       */
85      protected void fillBuffer() throws IOException {
86          if (eof) {
87              return;
88          }
89          int space = buffer.getSpace();
90          final byte[] buf = IOUtils.byteArray(space);
91          while (space > 0) {
92              final int res = in.read(buf, 0, space);
93              if (res == EOF) {
94                  eof = true;
95                  return;
96              }
97              if (res > 0) {
98                  buffer.add(buf, 0, res);
99                  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 }