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    *   http://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 org.jboss.netty.handler.codec.marshalling;
17  
18  import java.io.IOException;
19  
20  import org.jboss.marshalling.ByteInput;
21  import org.jboss.netty.buffer.ChannelBuffer;
22  
23  /**
24   * {@link ByteInput} implementation which reads its data from a {@link ChannelBuffer}
25   *
26   *
27   */
28  class ChannelBufferByteInput implements ByteInput {
29  
30      private final ChannelBuffer buffer;
31  
32      public ChannelBufferByteInput(ChannelBuffer buffer) {
33          this.buffer = buffer;
34      }
35  
36      public void close() throws IOException {
37          // nothing to do
38      }
39  
40      public int available() throws IOException {
41          return buffer.readableBytes();
42      }
43  
44      public int read() throws IOException {
45          if (buffer.readable()) {
46              return buffer.readByte() & 0xff;
47          }
48          return -1;
49      }
50  
51      public int read(byte[] array) throws IOException {
52          return read(array, 0, array.length);
53      }
54  
55      public int read(byte[] dst, int dstIndex, int length) throws IOException {
56          int available = available();
57          if (available == 0) {
58              return -1;
59          }
60  
61          length = Math.min(available, length);
62          buffer.readBytes(dst, dstIndex, length);
63          return length;
64      }
65  
66      public long skip(long bytes) throws IOException {
67          int readable = buffer.readableBytes();
68          if (readable < bytes) {
69              bytes = readable;
70          }
71          buffer.readerIndex((int) (buffer.readerIndex() + bytes));
72          return bytes;
73      }
74  
75  }