View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.spdy.api;
20  
21  import java.nio.ByteBuffer;
22  import java.util.concurrent.TimeUnit;
23  
24  /**
25   * <p>Specialized {@link DataInfo} for byte array content.</p>
26   */
27  public class BytesDataInfo extends DataInfo
28  {
29      private final byte[] bytes;
30      private final int offset;
31      private final int length;
32      private int index;
33  
34      public BytesDataInfo(byte[] bytes, boolean close)
35      {
36          this(0, TimeUnit.SECONDS, bytes, close);
37      }
38  
39      public BytesDataInfo(long timeout, TimeUnit unit, byte[] bytes, boolean close)
40      {
41          this(timeout, unit, bytes, 0, bytes.length, close);
42      }
43  
44      public BytesDataInfo(long timeout, TimeUnit unit, byte[] bytes, int offset, int length, boolean close)
45      {
46          super(timeout, unit, close);
47          this.bytes = bytes;
48          this.offset = offset;
49          this.length = length;
50          this.index = offset;
51      }
52  
53      @Override
54      public int length()
55      {
56          return length;
57      }
58  
59      @Override
60      public int available()
61      {
62          return length - index + offset;
63      }
64  
65      @Override
66      public int readInto(ByteBuffer output)
67      {
68          int space = output.remaining();
69          int chunk = Math.min(available(), space);
70          output.put(bytes, index, chunk);
71          index += chunk;
72          return chunk;
73      }
74  
75      @Override
76      public int readInto(byte[] bytes, int offset, int length)
77      {
78          int chunk = Math.min(available(), length);
79          System.arraycopy(this.bytes, index, bytes, offset, chunk);
80          index += chunk;
81          return chunk;
82      }
83  }