View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.http.impl.nio;
29  
30  import java.nio.BufferOverflowException;
31  import java.nio.ByteBuffer;
32  
33  /**
34   * A buffer that expand its capacity on demand. Internally, this class is backed
35   * by an instance of {@link ByteBuffer}.
36   * <p>
37   * This class is not thread safe.
38   *
39   * @since 4.0
40   */
41  public class ExpandableBuffer {
42  
43      public final static int INPUT_MODE = 0;
44      public final static int OUTPUT_MODE = 1;
45  
46      private int mode;
47      private ByteBuffer buffer;
48  
49      /**
50       * Allocates buffer of the given size using the given allocator.
51       *
52       * @param bufferSize the buffer size.
53       */
54      protected ExpandableBuffer(final int bufferSize) {
55          super();
56          this.buffer = ByteBuffer.allocate(bufferSize);
57          this.mode = INPUT_MODE;
58      }
59  
60      /**
61       * Returns the current mode:
62       * <p>
63       * {@link #INPUT_MODE}: the buffer is in the input mode.
64       * <p>
65       * {@link #OUTPUT_MODE}: the buffer is in the output mode.
66       *
67       * @return current input/output mode.
68       */
69      public int mode() {
70          return this.mode;
71      }
72  
73      public ByteBuffer buffer() {
74          return this.buffer;
75      }
76  
77      /**
78       * Sets output mode. The buffer can now be read from.
79       */
80      protected void setOutputMode() {
81          if (this.mode != OUTPUT_MODE) {
82              this.buffer.flip();
83              this.mode = OUTPUT_MODE;
84          }
85      }
86  
87      /**
88       * Sets input mode. The buffer can now be written into.
89       */
90      protected void setInputMode() {
91          if (this.mode != INPUT_MODE) {
92              if (this.buffer.hasRemaining()) {
93                  this.buffer.compact();
94              } else {
95                  this.buffer.clear();
96              }
97              this.mode = INPUT_MODE;
98          }
99      }
100 
101     private void expandCapacity(final int capacity) {
102         final ByteBuffer oldbuffer = this.buffer;
103         this.buffer = ByteBuffer.allocate(capacity);
104         oldbuffer.flip();
105         this.buffer.put(oldbuffer);
106     }
107 
108     /**
109      * Expands buffer's capacity.
110      *
111      * @throws BufferOverflowException in case we get over the maximum allowed value
112      */
113     protected void expand() throws BufferOverflowException {
114         int newcapacity = (this.buffer.capacity() + 1) << 1;
115         if (newcapacity < 0) {
116             final int vmBytes = Long.SIZE >> 3;
117             final int javaBytes = 8; // this is to be checked when the JVM version changes
118             @SuppressWarnings("unused") // we really need the 8 if we're going to make this foolproof
119             final int headRoom = (vmBytes >= javaBytes) ? vmBytes : javaBytes;
120             // Reason: In GC the size of objects is passed as int (2 bytes).
121             // Then, the header size of the objects is added to the size.
122             // Long has the longest header available. Object header seems to be linked to it.
123             // Details: I added a minimum of 8 just to be safe and because 8 is used in
124             // java.lang.Object.ArrayList: private static final int MAX_ARRAY_SIZE = 2147483639.
125             //
126             // WARNING: This code assumes you are providing enough heap room with -Xmx.
127             // source of inspiration: https://bugs.openjdk.java.net/browse/JDK-8059914
128             newcapacity = Integer.MAX_VALUE - headRoom;
129 
130             if (newcapacity <= this.buffer.capacity()) {
131                 throw new BufferOverflowException();
132             }
133         }
134         expandCapacity(newcapacity);
135     }
136 
137     /**
138      * Ensures the buffer can accommodate the required capacity.
139      */
140     protected void ensureCapacity(final int requiredCapacity) {
141         if (requiredCapacity > this.buffer.capacity()) {
142             expandCapacity(requiredCapacity);
143         }
144     }
145 
146     /**
147      * Determines if the buffer contains data.
148      *
149      * @return {@code true} if there is data in the buffer,
150      *   {@code false} otherwise.
151      */
152     public boolean hasData() {
153         setOutputMode();
154         return this.buffer.hasRemaining();
155     }
156 
157     /**
158      * Returns the length of this buffer.
159      *
160      * @return buffer length.
161      */
162     public int length() {
163         setOutputMode();
164         return this.buffer.remaining();
165     }
166 
167     /**
168      * Returns available capacity of this buffer.
169      *
170      * @return buffer length.
171      */
172     public int capacity() {
173         setInputMode();
174         return this.buffer.remaining();
175     }
176 
177     /**
178      * Clears buffer.
179      */
180     protected void clear() {
181         this.buffer.clear();
182         this.mode = INPUT_MODE;
183     }
184 
185     @Override
186     public String toString() {
187         final StringBuilder sb = new StringBuilder();
188         sb.append("[mode=");
189         if (mode() == INPUT_MODE) {
190             sb.append("in");
191         } else {
192             sb.append("out");
193         }
194         sb.append(" pos=");
195         sb.append(this.buffer.position());
196         sb.append(" lim=");
197         sb.append(this.buffer.limit());
198         sb.append(" cap=");
199         sb.append(this.buffer.capacity());
200         sb.append("]");
201         return sb.toString();
202     }
203 
204 }