Buffer.java revision 934767b07d94041390785d8fe66c86b2379730bc
1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package java.nio;
18
19/**
20 * A buffer is a list of elements of a specific primitive type.
21 * <p>
22 * A buffer can be described by the following properties:
23 * <ul>
24 * <li>Capacity: the number of elements a buffer can hold. Capacity may not be
25 * negative and never changes.</li>
26 * <li>Position: a cursor of this buffer. Elements are read or written at the
27 * position if you do not specify an index explicitly. Position may not be
28 * negative and not greater than the limit.</li>
29 * <li>Limit: controls the scope of accessible elements. You can only read or
30 * write elements from index zero to <code>limit - 1</code>. Accessing
31 * elements out of the scope will cause an exception. Limit may not be negative
32 * and not greater than capacity.</li>
33 * <li>Mark: used to remember the current position, so that you can reset the
34 * position later. Mark may not be negative and no greater than position.</li>
35 * <li>A buffer can be read-only or read-write. Trying to modify the elements
36 * of a read-only buffer will cause a <code>ReadOnlyBufferException</code>,
37 * while changing the position, limit and mark of a read-only buffer is OK.</li>
38 * <li>A buffer can be direct or indirect. A direct buffer will try its best to
39 * take advantage of native memory APIs and it may not stay in the Java heap,
40 * thus it is not affected by garbage collection.</li>
41 * </ul>
42 * <p>
43 * Buffers are not thread-safe. If concurrent access to a buffer instance is
44 * required, then the callers are responsible to take care of the
45 * synchronization issues.
46 */
47public abstract class Buffer {
48
49    static final int SIZEOF_CHAR = 2;
50    static final int SIZEOF_DOUBLE = 8;
51    static final int SIZEOF_FLOAT = 4;
52    static final int SIZEOF_INT = 4;
53    static final int SIZEOF_LONG = 8;
54    static final int SIZEOF_SHORT = 2;
55
56    /**
57     * <code>UNSET_MARK</code> means the mark has not been set.
58     */
59    static final int UNSET_MARK = -1;
60
61    /**
62     * The capacity of this buffer, which never changes.
63     */
64    final int capacity;
65
66    /**
67     * <code>limit - 1</code> is the last element that can be read or written.
68     * Limit must be no less than zero and no greater than <code>capacity</code>.
69     */
70    int limit;
71
72    /**
73     * Mark is where position will be set when <code>reset()</code> is called.
74     * Mark is not set by default. Mark is always no less than zero and no
75     * greater than <code>position</code>.
76     */
77    int mark = UNSET_MARK;
78
79    /**
80     * The current position of this buffer. Position is always no less than zero
81     * and no greater than <code>limit</code>.
82     */
83    int position = 0;
84
85    /**
86     * The log base 2 of the element size of this buffer.  Each typed subclass
87     * (ByteBuffer, CharBuffer, etc.) is responsible for initializing this
88     * value.  The value is used by JNI code in frameworks/base/ to avoid the
89     * need for costly 'instanceof' tests.
90     */
91    final int _elementSizeShift;
92
93    /**
94     * For direct buffers, the effective address of the data; zero otherwise.
95     * This is set in the constructor.
96     * TODO: make this final at the cost of loads of extra constructors? [how many?]
97     */
98    int effectiveDirectAddress;
99
100    /**
101     * For direct buffers, the underlying MemoryBlock; null otherwise.
102     */
103    final MemoryBlock block;
104
105    Buffer(int elementSizeShift, int capacity, MemoryBlock block) {
106        this._elementSizeShift = elementSizeShift;
107        if (capacity < 0) {
108            throw new IllegalArgumentException("capacity < 0: " + capacity);
109        }
110        this.capacity = this.limit = capacity;
111        this.block = block;
112    }
113
114    /**
115     * Returns the array that backs this buffer (optional operation).
116     * The returned value is the actual array, not a copy, so modifications
117     * to the array write through to the buffer.
118     *
119     * <p>Subclasses should override this method with a covariant return type
120     * to provide the exact type of the array.
121     *
122     * <p>Use {@code hasArray} to ensure this method won't throw.
123     * (A separate call to {@code isReadOnly} is not necessary.)
124     *
125     * @return the array
126     * @throws ReadOnlyBufferException if the buffer is read-only
127     *         UnsupportedOperationException if the buffer does not expose an array
128     * @since 1.6
129     */
130    public abstract Object array();
131
132    /**
133     * Returns the offset into the array returned by {@code array} of the first
134     * element of the buffer (optional operation). The backing array (if there is one)
135     * is not necessarily the same size as the buffer, and position 0 in the buffer is
136     * not necessarily the 0th element in the array. Use
137     * {@code buffer.array()[offset + buffer.arrayOffset()} to access element {@code offset}
138     * in {@code buffer}.
139     *
140     * <p>Use {@code hasArray} to ensure this method won't throw.
141     * (A separate call to {@code isReadOnly} is not necessary.)
142     *
143     * @return the offset
144     * @throws ReadOnlyBufferException if the buffer is read-only
145     *         UnsupportedOperationException if the buffer does not expose an array
146     * @since 1.6
147     */
148    public abstract int arrayOffset();
149
150    /**
151     * Returns the capacity of this buffer.
152     *
153     * @return the number of elements that are contained in this buffer.
154     */
155    public final int capacity() {
156        return capacity;
157    }
158
159    /**
160     * Clears this buffer.
161     * <p>
162     * While the content of this buffer is not changed, the following internal
163     * changes take place: the current position is reset back to the start of
164     * the buffer, the value of the buffer limit is made equal to the capacity
165     * and mark is cleared.
166     *
167     * @return this buffer.
168     */
169    public final Buffer clear() {
170        position = 0;
171        mark = UNSET_MARK;
172        limit = capacity;
173        return this;
174    }
175
176    /**
177     * Flips this buffer.
178     * <p>
179     * The limit is set to the current position, then the position is set to
180     * zero, and the mark is cleared.
181     * <p>
182     * The content of this buffer is not changed.
183     *
184     * @return this buffer.
185     */
186    public final Buffer flip() {
187        limit = position;
188        position = 0;
189        mark = UNSET_MARK;
190        return this;
191    }
192
193    /**
194     * Returns true if {@code array} and {@code arrayOffset} won't throw. This method does not
195     * return true for buffers not backed by arrays because the other methods would throw
196     * {@code UnsupportedOperationException}, nor does it return true for buffers backed by
197     * read-only arrays, because the other methods would throw {@code ReadOnlyBufferException}.
198     * @since 1.6
199     */
200    public abstract boolean hasArray();
201
202    /**
203     * Indicates if there are elements remaining in this buffer, that is if
204     * {@code position < limit}.
205     *
206     * @return {@code true} if there are elements remaining in this buffer,
207     *         {@code false} otherwise.
208     */
209    public final boolean hasRemaining() {
210        return position < limit;
211    }
212
213    /**
214     * Returns true if this is a direct buffer.
215     * @since 1.6
216     */
217    public abstract boolean isDirect();
218
219    /**
220     * Indicates whether this buffer is read-only.
221     *
222     * @return {@code true} if this buffer is read-only, {@code false}
223     *         otherwise.
224     */
225    public abstract boolean isReadOnly();
226
227    /**
228     * Returns the limit of this buffer.
229     *
230     * @return the limit of this buffer.
231     */
232    public final int limit() {
233        return limit;
234    }
235
236    /**
237     * Sets the limit of this buffer.
238     * <p>
239     * If the current position in the buffer is in excess of
240     * <code>newLimit</code> then, on returning from this call, it will have
241     * been adjusted to be equivalent to <code>newLimit</code>. If the mark
242     * is set and is greater than the new limit, then it is cleared.
243     *
244     * @param newLimit
245     *            the new limit, must not be negative and not greater than
246     *            capacity.
247     * @return this buffer.
248     * @exception IllegalArgumentException
249     *                if <code>newLimit</code> is invalid.
250     */
251    public final Buffer limit(int newLimit) {
252        if (newLimit < 0 || newLimit > capacity) {
253            throw new IllegalArgumentException();
254        }
255
256        limit = newLimit;
257        if (position > newLimit) {
258            position = newLimit;
259        }
260        if ((mark != UNSET_MARK) && (mark > newLimit)) {
261            mark = UNSET_MARK;
262        }
263        return this;
264    }
265
266    /**
267     * Marks the current position, so that the position may return to this point
268     * later by calling <code>reset()</code>.
269     *
270     * @return this buffer.
271     */
272    public final Buffer mark() {
273        mark = position;
274        return this;
275    }
276
277    /**
278     * Returns the position of this buffer.
279     *
280     * @return the value of this buffer's current position.
281     */
282    public final int position() {
283        return position;
284    }
285
286    /**
287     * Sets the position of this buffer.
288     * <p>
289     * If the mark is set and it is greater than the new position, then it is
290     * cleared.
291     *
292     * @param newPosition
293     *            the new position, must be not negative and not greater than
294     *            limit.
295     * @return this buffer.
296     * @exception IllegalArgumentException
297     *                if <code>newPosition</code> is invalid.
298     */
299    public final Buffer position(int newPosition) {
300        if (newPosition < 0 || newPosition > limit) {
301            throw new IllegalArgumentException();
302        }
303
304        position = newPosition;
305        if ((mark != UNSET_MARK) && (mark > position)) {
306            mark = UNSET_MARK;
307        }
308        return this;
309    }
310
311    /**
312     * Returns the number of remaining elements in this buffer, that is
313     * {@code limit - position}.
314     *
315     * @return the number of remaining elements in this buffer.
316     */
317    public final int remaining() {
318        return limit - position;
319    }
320
321    /**
322     * Resets the position of this buffer to the <code>mark</code>.
323     *
324     * @return this buffer.
325     * @exception InvalidMarkException
326     *                if the mark is not set.
327     */
328    public final Buffer reset() {
329        if (mark == UNSET_MARK) {
330            throw new InvalidMarkException();
331        }
332        position = mark;
333        return this;
334    }
335
336    /**
337     * Rewinds this buffer.
338     * <p>
339     * The position is set to zero, and the mark is cleared. The content of this
340     * buffer is not changed.
341     *
342     * @return this buffer.
343     */
344    public final Buffer rewind() {
345        position = 0;
346        mark = UNSET_MARK;
347        return this;
348    }
349}
350