View Javadoc

1   //========================================================================
2   //Copyright 2011-2012 Mort Bay Consulting Pty. Ltd.
3   //------------------------------------------------------------------------
4   //All rights reserved. This program and the accompanying materials
5   //are made available under the terms of the Eclipse Public License v1.0
6   //and Apache License v2.0 which accompanies this distribution.
7   //The Eclipse Public License is available at
8   //http://www.eclipse.org/legal/epl-v10.html
9   //The Apache License v2.0 is available at
10  //http://www.opensource.org/licenses/apache2.0.php
11  //You may elect to redistribute this code under either of these licenses.
12  //========================================================================
13  
14  package org.eclipse.jetty.spdy.api;
15  
16  import java.nio.ByteBuffer;
17  
18  /**
19   * <p>Specialized {@link DataInfo} for {@link ByteBuffer} content.</p>
20   */
21  public class ByteBufferDataInfo extends DataInfo
22  {
23      private final ByteBuffer buffer;
24      private final int length;
25  
26      public ByteBufferDataInfo(ByteBuffer buffer, boolean close)
27      {
28          this(buffer, close, false);
29      }
30  
31      public ByteBufferDataInfo(ByteBuffer buffer, boolean close, boolean compress)
32      {
33          super(close, compress);
34          this.buffer = buffer;
35          this.length = buffer.remaining();
36      }
37  
38      @Override
39      public int length()
40      {
41          return length;
42      }
43  
44      @Override
45      public int available()
46      {
47          return buffer.remaining();
48      }
49  
50      @Override
51      public int readInto(ByteBuffer output)
52      {
53          int space = output.remaining();
54          if (available() > space)
55          {
56              int limit = buffer.limit();
57              buffer.limit(buffer.position() + space);
58              output.put(buffer);
59              buffer.limit(limit);
60          }
61          else
62          {
63              space = buffer.remaining();
64              output.put(buffer);
65          }
66          return space;
67      }
68  
69      @Override
70      protected ByteBuffer allocate(int size)
71      {
72          return buffer.isDirect() ? ByteBuffer.allocateDirect(size) : super.allocate(size);
73      }
74  }