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  
23  /**
24   * <p>Specialized {@link DataInfo} for {@link ByteBuffer} content.</p>
25   */
26  public class ByteBufferDataInfo extends DataInfo
27  {
28      private final ByteBuffer buffer;
29      private final int length;
30  
31      public ByteBufferDataInfo(ByteBuffer buffer, boolean close)
32      {
33          this(buffer, close, false);
34      }
35  
36      public ByteBufferDataInfo(ByteBuffer buffer, boolean close, boolean compress)
37      {
38          super(close, compress);
39          this.buffer = buffer;
40          this.length = buffer.remaining();
41      }
42  
43      @Override
44      public int length()
45      {
46          return length;
47      }
48  
49      @Override
50      public int available()
51      {
52          return buffer.remaining();
53      }
54  
55      @Override
56      public int readInto(ByteBuffer output)
57      {
58          int space = output.remaining();
59          if (available() > space)
60          {
61              int limit = buffer.limit();
62              buffer.limit(buffer.position() + space);
63              output.put(buffer);
64              buffer.limit(limit);
65          }
66          else
67          {
68              space = buffer.remaining();
69              output.put(buffer);
70          }
71          return space;
72      }
73  
74      @Override
75      protected ByteBuffer allocate(int size)
76      {
77          return buffer.isDirect() ? ByteBuffer.allocateDirect(size) : super.allocate(size);
78      }
79  }