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 {@link ByteBuffer} content.</p>
26   */
27  public class ByteBufferDataInfo extends DataInfo
28  {
29      private final ByteBuffer buffer;
30      private final int length;
31  
32      public ByteBufferDataInfo(ByteBuffer buffer, boolean close)
33      {
34          this(0, TimeUnit.SECONDS, buffer, close);
35      }
36  
37      public ByteBufferDataInfo(long timeout, TimeUnit unit, ByteBuffer buffer, boolean close)
38      {
39          super(timeout, unit, close);
40          this.buffer = buffer;
41          this.length = buffer.remaining();
42      }
43  
44      @Override
45      public int length()
46      {
47          return length;
48      }
49  
50      @Override
51      public int available()
52      {
53          return buffer.remaining();
54      }
55  
56      @Override
57      public int readInto(ByteBuffer output)
58      {
59          int space = output.remaining();
60          if (available() > space)
61          {
62              int limit = buffer.limit();
63              buffer.limit(buffer.position() + space);
64              output.put(buffer);
65              buffer.limit(limit);
66          }
67          else
68          {
69              space = buffer.remaining();
70              output.put(buffer);
71          }
72          return space;
73      }
74  
75      @Override
76      public int readInto(byte[] bytes, int offset, int length)
77      {
78          int available = available();
79          if (available < length)
80              length = available;
81          buffer.get(bytes, offset, length);
82          return length;
83      }
84  
85      @Override
86      protected ByteBuffer allocate(int size)
87      {
88          return buffer.isDirect() ? ByteBuffer.allocateDirect(size) : super.allocate(size);
89      }
90  }