View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.buffer;
17  
18  import static io.netty.util.internal.MathUtil.isOutOfBounds;
19  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
20  
21  import io.netty.util.ReferenceCounted;
22  import io.netty.util.internal.ObjectUtil;
23  import io.netty.util.internal.StringUtil;
24  
25  import java.io.DataInput;
26  import java.io.DataInputStream;
27  import java.io.EOFException;
28  import java.io.IOException;
29  import java.io.InputStream;
30  
31  /**
32   * An {@link InputStream} which reads data from a {@link ByteBuf}.
33   * <p>
34   * A read operation against this stream will occur at the {@code readerIndex}
35   * of its underlying buffer and the {@code readerIndex} will increase during
36   * the read operation.  Please note that it only reads up to the number of
37   * readable bytes determined at the moment of construction.  Therefore,
38   * updating {@link ByteBuf#writerIndex()} will not affect the return
39   * value of {@link #available()}.
40   * <p>
41   * This stream implements {@link DataInput} for your convenience.
42   * The endianness of the stream is not always big endian but depends on
43   * the endianness of the underlying buffer.
44   *
45   * @see ByteBufOutputStream
46   */
47  public class ByteBufInputStream extends InputStream implements DataInput {
48      private final ByteBuf buffer;
49      private final int startIndex;
50      private final int endIndex;
51      private boolean closed;
52      /**
53       * To preserve backwards compatibility (which didn't transfer ownership) we support a conditional flag which
54       * indicates if {@link #buffer} should be released when this {@link InputStream} is closed.
55       * However in future releases ownership should always be transferred and callers of this class should call
56       * {@link ReferenceCounted#retain()} if necessary.
57       */
58      private final boolean releaseOnClose;
59  
60      /**
61       * Creates a new stream which reads data from the specified {@code buffer}
62       * starting at the current {@code readerIndex} and ending at the current
63       * {@code writerIndex}.
64       * @param buffer The buffer which provides the content for this {@link InputStream}.
65       */
66      public ByteBufInputStream(ByteBuf buffer) {
67          this(buffer, buffer.readableBytes());
68      }
69  
70      /**
71       * Creates a new stream which reads data from the specified {@code buffer}
72       * starting at the current {@code readerIndex} and ending at
73       * {@code readerIndex + length}.
74       * @param buffer The buffer which provides the content for this {@link InputStream}.
75       * @param length The length of the buffer to use for this {@link InputStream}.
76       * @throws IndexOutOfBoundsException
77       *         if {@code readerIndex + length} is greater than
78       *            {@code writerIndex}
79       */
80      public ByteBufInputStream(ByteBuf buffer, int length) {
81          this(buffer, length, false);
82      }
83  
84      /**
85       * Creates a new stream which reads data from the specified {@code buffer}
86       * starting at the current {@code readerIndex} and ending at the current
87       * {@code writerIndex}.
88       * @param buffer The buffer which provides the content for this {@link InputStream}.
89       * @param releaseOnClose {@code true} means that when {@link #close()} is called then {@link ByteBuf#release()} will
90       *                       be called on {@code buffer}.
91       */
92      public ByteBufInputStream(ByteBuf buffer, boolean releaseOnClose) {
93          this(buffer, buffer.readableBytes(), releaseOnClose);
94      }
95  
96      /**
97       * Creates a new stream which reads data from the specified {@code buffer}
98       * starting at the current {@code readerIndex} and ending at
99       * {@code readerIndex + length}.
100      * @param buffer The buffer which provides the content for this {@link InputStream}.
101      * @param length The length of the buffer to use for this {@link InputStream}.
102      * @param releaseOnClose {@code true} means that when {@link #close()} is called then {@link ByteBuf#release()} will
103      *                       be called on {@code buffer}.
104      * @throws IndexOutOfBoundsException
105      *         if {@code readerIndex + length} is greater than
106      *            {@code writerIndex}
107      */
108     public ByteBufInputStream(ByteBuf buffer, int length, boolean releaseOnClose) {
109         ObjectUtil.checkNotNull(buffer, "buffer");
110         if (length < 0) {
111             if (releaseOnClose) {
112                 buffer.release();
113             }
114             checkPositiveOrZero(length, "length");
115         }
116         if (length > buffer.readableBytes()) {
117             if (releaseOnClose) {
118                 buffer.release();
119             }
120             throw new IndexOutOfBoundsException("Too many bytes to be read - Needs "
121                     + length + ", maximum is " + buffer.readableBytes());
122         }
123 
124         this.releaseOnClose = releaseOnClose;
125         this.buffer = buffer;
126         startIndex = buffer.readerIndex();
127         endIndex = startIndex + length;
128         buffer.markReaderIndex();
129     }
130 
131     /**
132      * Returns the number of read bytes by this stream so far.
133      */
134     public int readBytes() {
135         return buffer.readerIndex() - startIndex;
136     }
137 
138     @Override
139     public void close() throws IOException {
140         try {
141             super.close();
142         } finally {
143             // The Closable interface says "If the stream is already closed then invoking this method has no effect."
144             if (releaseOnClose && !closed) {
145                 closed = true;
146                 buffer.release();
147             }
148         }
149     }
150 
151     @Override
152     public int available() throws IOException {
153         return endIndex - buffer.readerIndex();
154     }
155 
156     // Suppress a warning since the class is not thread-safe
157     @Override
158     public void mark(int readlimit) {
159         buffer.markReaderIndex();
160     }
161 
162     @Override
163     public boolean markSupported() {
164         return true;
165     }
166 
167     @Override
168     public int read() throws IOException {
169         int available = available();
170         if (available == 0) {
171             return -1;
172         }
173         return buffer.readByte() & 0xff;
174     }
175 
176     @Override
177     public int read(byte[] b, int off, int len) throws IOException {
178         ObjectUtil.checkNotNull(b, "b");
179         if (isOutOfBounds(off, len, b.length)) {
180             throw new IndexOutOfBoundsException();
181         }
182         if (len == 0) {
183             return 0;
184         }
185         int available = available();
186         if (available == 0) {
187             return -1;
188         }
189 
190         len = Math.min(available, len);
191         buffer.readBytes(b, off, len);
192         return len;
193     }
194 
195     // Suppress a warning since the class is not thread-safe
196     @Override
197     public void reset() throws IOException {
198         buffer.resetReaderIndex();
199     }
200 
201     @Override
202     public long skip(long n) throws IOException {
203         if (n <= 0) {
204             return 0;
205         }
206         if (n > Integer.MAX_VALUE) {
207             return skipBytes(Integer.MAX_VALUE);
208         } else {
209             return skipBytes((int) n);
210         }
211     }
212 
213     @Override
214     public boolean readBoolean() throws IOException {
215         checkAvailable(1);
216         return read() != 0;
217     }
218 
219     @Override
220     public byte readByte() throws IOException {
221         checkAvailable(1);
222         return buffer.readByte();
223     }
224 
225     @Override
226     public char readChar() throws IOException {
227         return (char) readShort();
228     }
229 
230     @Override
231     public double readDouble() throws IOException {
232         return Double.longBitsToDouble(readLong());
233     }
234 
235     @Override
236     public float readFloat() throws IOException {
237         return Float.intBitsToFloat(readInt());
238     }
239 
240     @Override
241     public void readFully(byte[] b) throws IOException {
242         readFully(b, 0, b.length);
243     }
244 
245     @Override
246     public void readFully(byte[] b, int off, int len) throws IOException {
247         checkAvailable(len);
248         buffer.readBytes(b, off, len);
249     }
250 
251     @Override
252     public int readInt() throws IOException {
253         checkAvailable(4);
254         return buffer.readInt();
255     }
256 
257     private StringBuilder lineBuf;
258 
259     @Override
260     public String readLine() throws IOException {
261         int available = available();
262         if (available == 0) {
263             return null;
264         }
265 
266         if (lineBuf != null) {
267             lineBuf.setLength(0);
268         }
269 
270         loop: do {
271             int c = buffer.readUnsignedByte();
272             --available;
273             switch (c) {
274                 case '\n':
275                     break loop;
276 
277                 case '\r':
278                     if (available > 0 && (char) buffer.getUnsignedByte(buffer.readerIndex()) == '\n') {
279                         buffer.skipBytes(1);
280                         --available;
281                     }
282                     break loop;
283 
284                 default:
285                     if (lineBuf == null) {
286                         lineBuf = new StringBuilder();
287                     }
288                     lineBuf.append((char) c);
289             }
290         } while (available > 0);
291 
292         return lineBuf != null && lineBuf.length() > 0 ? lineBuf.toString() : StringUtil.EMPTY_STRING;
293     }
294 
295     @Override
296     public long readLong() throws IOException {
297         checkAvailable(8);
298         return buffer.readLong();
299     }
300 
301     @Override
302     public short readShort() throws IOException {
303         checkAvailable(2);
304         return buffer.readShort();
305     }
306 
307     @Override
308     public String readUTF() throws IOException {
309         return DataInputStream.readUTF(this);
310     }
311 
312     @Override
313     public int readUnsignedByte() throws IOException {
314         return readByte() & 0xff;
315     }
316 
317     @Override
318     public int readUnsignedShort() throws IOException {
319         return readShort() & 0xffff;
320     }
321 
322     @Override
323     public int skipBytes(int n) throws IOException {
324         if (n <= 0) {
325             return 0;
326         }
327         int nBytes = Math.min(available(), n);
328         buffer.skipBytes(nBytes);
329         return nBytes;
330     }
331 
332     private void checkAvailable(int fieldSize) throws IOException {
333         if (fieldSize < 0) {
334             throw new IndexOutOfBoundsException("fieldSize cannot be a negative number");
335         }
336         if (fieldSize > available()) {
337             throw new EOFException("fieldSize is too long! Length is " + fieldSize
338                     + ", but maximum is " + available());
339         }
340     }
341 }