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