001 /*
002 * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation. Sun designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Sun in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022 * CA 95054 USA or visit www.sun.com if you need additional information or
023 * have any questions.
024 */
025
026 package java.nio;
027
028 /**
029 * A container for data of a specific primitive type.
030 *
031 * <p> A buffer is a linear, finite sequence of elements of a specific
032 * primitive type. Aside from its content, the essential properties of a
033 * buffer are its capacity, limit, and position: </p>
034 *
035 * <blockquote>
036 *
037 * <p> A buffer's <i>capacity</i> is the number of elements it contains. The
038 * capacity of a buffer is never negative and never changes. </p>
039 *
040 * <p> A buffer's <i>limit</i> is the index of the first element that should
041 * not be read or written. A buffer's limit is never negative and is never
042 * greater than its capacity. </p>
043 *
044 * <p> A buffer's <i>position</i> is the index of the next element to be
045 * read or written. A buffer's position is never negative and is never
046 * greater than its limit. </p>
047 *
048 * </blockquote>
049 *
050 * <p> There is one subclass of this class for each non-boolean primitive type.
051 *
052 *
053 * <h4> Transferring data </h4>
054 *
055 * <p> Each subclass of this class defines two categories of <i>get</i> and
056 * <i>put</i> operations: </p>
057 *
058 * <blockquote>
059 *
060 * <p> <i>Relative</i> operations read or write one or more elements starting
061 * at the current position and then increment the position by the number of
062 * elements transferred. If the requested transfer exceeds the limit then a
063 * relative <i>get</i> operation throws a {@link BufferUnderflowException}
064 * and a relative <i>put</i> operation throws a {@link
065 * BufferOverflowException}; in either case, no data is transferred. </p>
066 *
067 * <p> <i>Absolute</i> operations take an explicit element index and do not
068 * affect the position. Absolute <i>get</i> and <i>put</i> operations throw
069 * an {@link IndexOutOfBoundsException} if the index argument exceeds the
070 * limit. </p>
071 *
072 * </blockquote>
073 *
074 * <p> Data may also, of course, be transferred in to or out of a buffer by the
075 * I/O operations of an appropriate channel, which are always relative to the
076 * current position.
077 *
078 *
079 * <h4> Marking and resetting </h4>
080 *
081 * <p> A buffer's <i>mark</i> is the index to which its position will be reset
082 * when the {@link #reset reset} method is invoked. The mark is not always
083 * defined, but when it is defined it is never negative and is never greater
084 * than the position. If the mark is defined then it is discarded when the
085 * position or the limit is adjusted to a value smaller than the mark. If the
086 * mark is not defined then invoking the {@link #reset reset} method causes an
087 * {@link InvalidMarkException} to be thrown.
088 *
089 *
090 * <h4> Invariants </h4>
091 *
092 * <p> The following invariant holds for the mark, position, limit, and
093 * capacity values:
094 *
095 * <blockquote>
096 * <tt>0</tt> <tt><=</tt>
097 * <i>mark</i> <tt><=</tt>
098 * <i>position</i> <tt><=</tt>
099 * <i>limit</i> <tt><=</tt>
100 * <i>capacity</i>
101 * </blockquote>
102 *
103 * <p> A newly-created buffer always has a position of zero and a mark that is
104 * undefined. The initial limit may be zero, or it may be some other value
105 * that depends upon the type of the buffer and the manner in which it is
106 * constructed. Each element of a newly-allocated buffer is initialized
107 * to zero.
108 *
109 *
110 * <h4> Clearing, flipping, and rewinding </h4>
111 *
112 * <p> In addition to methods for accessing the position, limit, and capacity
113 * values and for marking and resetting, this class also defines the following
114 * operations upon buffers:
115 *
116 * <ul>
117 *
118 * <li><p> {@link #clear} makes a buffer ready for a new sequence of
119 * channel-read or relative <i>put</i> operations: It sets the limit to the
120 * capacity and the position to zero. </p></li>
121 *
122 * <li><p> {@link #flip} makes a buffer ready for a new sequence of
123 * channel-write or relative <i>get</i> operations: It sets the limit to the
124 * current position and then sets the position to zero. </p></li>
125 *
126 * <li><p> {@link #rewind} makes a buffer ready for re-reading the data that
127 * it already contains: It leaves the limit unchanged and sets the position
128 * to zero. </p></li>
129 *
130 * </ul>
131 *
132 *
133 * <h4> Read-only buffers </h4>
134 *
135 * <p> Every buffer is readable, but not every buffer is writable. The
136 * mutation methods of each buffer class are specified as <i>optional
137 * operations</i> that will throw a {@link ReadOnlyBufferException} when
138 * invoked upon a read-only buffer. A read-only buffer does not allow its
139 * content to be changed, but its mark, position, and limit values are mutable.
140 * Whether or not a buffer is read-only may be determined by invoking its
141 * {@link #isReadOnly isReadOnly} method.
142 *
143 *
144 * <h4> Thread safety </h4>
145 *
146 * <p> Buffers are not safe for use by multiple concurrent threads. If a
147 * buffer is to be used by more than one thread then access to the buffer
148 * should be controlled by appropriate synchronization.
149 *
150 *
151 * <h4> Invocation chaining </h4>
152 *
153 * <p> Methods in this class that do not otherwise have a value to return are
154 * specified to return the buffer upon which they are invoked. This allows
155 * method invocations to be chained; for example, the sequence of statements
156 *
157 * <blockquote><pre>
158 * b.flip();
159 * b.position(23);
160 * b.limit(42);</pre></blockquote>
161 *
162 * can be replaced by the single, more compact statement
163 *
164 * <blockquote><pre>
165 * b.flip().position(23).limit(42);</pre></blockquote>
166 *
167 *
168 * @author Mark Reinhold
169 * @author JSR-51 Expert Group
170 * @since 1.4
171 */
172
173 public abstract class Buffer {
174
175 // Invariants: mark <= position <= limit <= capacity
176 private int mark = -1;
177 private int position = 0;
178 private int limit;
179 private int capacity;
180
181 // Used only by direct buffers
182 // NOTE: hoisted here for speed in JNI GetDirectBufferAddress
183 long address;
184
185 // Creates a new buffer with the given mark, position, limit, and capacity,
186 // after checking invariants.
187 //
188 Buffer(int mark, int pos, int lim, int cap) { // package-private
189 if (cap < 0)
190 throw new IllegalArgumentException("Negative capacity: "
191 + cap);
192 this .capacity = cap;
193 limit(lim);
194 position(pos);
195 if (mark >= 0) {
196 if (mark > pos)
197 throw new IllegalArgumentException("mark > position: ("
198 + mark + " > " + pos + ")");
199 this .mark = mark;
200 }
201 }
202
203 /**
204 * Returns this buffer's capacity. </p>
205 *
206 * @return The capacity of this buffer
207 */
208 public final int capacity() {
209 return capacity;
210 }
211
212 /**
213 * Returns this buffer's position. </p>
214 *
215 * @return The position of this buffer
216 */
217 public final int position() {
218 return position;
219 }
220
221 /**
222 * Sets this buffer's position. If the mark is defined and larger than the
223 * new position then it is discarded. </p>
224 *
225 * @param newPosition
226 * The new position value; must be non-negative
227 * and no larger than the current limit
228 *
229 * @return This buffer
230 *
231 * @throws IllegalArgumentException
232 * If the preconditions on <tt>newPosition</tt> do not hold
233 */
234 public final Buffer position(int newPosition) {
235 if ((newPosition > limit) || (newPosition < 0))
236 throw new IllegalArgumentException();
237 position = newPosition;
238 if (mark > position)
239 mark = -1;
240 return this ;
241 }
242
243 /**
244 * Returns this buffer's limit. </p>
245 *
246 * @return The limit of this buffer
247 */
248 public final int limit() {
249 return limit;
250 }
251
252 /**
253 * Sets this buffer's limit. If the position is larger than the new limit
254 * then it is set to the new limit. If the mark is defined and larger than
255 * the new limit then it is discarded. </p>
256 *
257 * @param newLimit
258 * The new limit value; must be non-negative
259 * and no larger than this buffer's capacity
260 *
261 * @return This buffer
262 *
263 * @throws IllegalArgumentException
264 * If the preconditions on <tt>newLimit</tt> do not hold
265 */
266 public final Buffer limit(int newLimit) {
267 if ((newLimit > capacity) || (newLimit < 0))
268 throw new IllegalArgumentException();
269 limit = newLimit;
270 if (position > limit)
271 position = limit;
272 if (mark > limit)
273 mark = -1;
274 return this ;
275 }
276
277 /**
278 * Sets this buffer's mark at its position. </p>
279 *
280 * @return This buffer
281 */
282 public final Buffer mark() {
283 mark = position;
284 return this ;
285 }
286
287 /**
288 * Resets this buffer's position to the previously-marked position.
289 *
290 * <p> Invoking this method neither changes nor discards the mark's
291 * value. </p>
292 *
293 * @return This buffer
294 *
295 * @throws InvalidMarkException
296 * If the mark has not been set
297 */
298 public final Buffer reset() {
299 int m = mark;
300 if (m < 0)
301 throw new InvalidMarkException();
302 position = m;
303 return this ;
304 }
305
306 /**
307 * Clears this buffer. The position is set to zero, the limit is set to
308 * the capacity, and the mark is discarded.
309 *
310 * <p> Invoke this method before using a sequence of channel-read or
311 * <i>put</i> operations to fill this buffer. For example:
312 *
313 * <blockquote><pre>
314 * buf.clear(); // Prepare buffer for reading
315 * in.read(buf); // Read data</pre></blockquote>
316 *
317 * <p> This method does not actually erase the data in the buffer, but it
318 * is named as if it did because it will most often be used in situations
319 * in which that might as well be the case. </p>
320 *
321 * @return This buffer
322 */
323 public final Buffer clear() {
324 position = 0;
325 limit = capacity;
326 mark = -1;
327 return this ;
328 }
329
330 /**
331 * Flips this buffer. The limit is set to the current position and then
332 * the position is set to zero. If the mark is defined then it is
333 * discarded.
334 *
335 * <p> After a sequence of channel-read or <i>put</i> operations, invoke
336 * this method to prepare for a sequence of channel-write or relative
337 * <i>get</i> operations. For example:
338 *
339 * <blockquote><pre>
340 * buf.put(magic); // Prepend header
341 * in.read(buf); // Read data into rest of buffer
342 * buf.flip(); // Flip buffer
343 * out.write(buf); // Write header + data to channel</pre></blockquote>
344 *
345 * <p> This method is often used in conjunction with the {@link
346 * java.nio.ByteBuffer#compact compact} method when transferring data from
347 * one place to another. </p>
348 *
349 * @return This buffer
350 */
351 public final Buffer flip() {
352 limit = position;
353 position = 0;
354 mark = -1;
355 return this ;
356 }
357
358 /**
359 * Rewinds this buffer. The position is set to zero and the mark is
360 * discarded.
361 *
362 * <p> Invoke this method before a sequence of channel-write or <i>get</i>
363 * operations, assuming that the limit has already been set
364 * appropriately. For example:
365 *
366 * <blockquote><pre>
367 * out.write(buf); // Write remaining data
368 * buf.rewind(); // Rewind buffer
369 * buf.get(array); // Copy data into array</pre></blockquote>
370 *
371 * @return This buffer
372 */
373 public final Buffer rewind() {
374 position = 0;
375 mark = -1;
376 return this ;
377 }
378
379 /**
380 * Returns the number of elements between the current position and the
381 * limit. </p>
382 *
383 * @return The number of elements remaining in this buffer
384 */
385 public final int remaining() {
386 return limit - position;
387 }
388
389 /**
390 * Tells whether there are any elements between the current position and
391 * the limit. </p>
392 *
393 * @return <tt>true</tt> if, and only if, there is at least one element
394 * remaining in this buffer
395 */
396 public final boolean hasRemaining() {
397 return position < limit;
398 }
399
400 /**
401 * Tells whether or not this buffer is read-only. </p>
402 *
403 * @return <tt>true</tt> if, and only if, this buffer is read-only
404 */
405 public abstract boolean isReadOnly();
406
407 /**
408 * Tells whether or not this buffer is backed by an accessible
409 * array.
410 *
411 * <p> If this method returns <tt>true</tt> then the {@link #array() array}
412 * and {@link #arrayOffset() arrayOffset} methods may safely be invoked.
413 * </p>
414 *
415 * @return <tt>true</tt> if, and only if, this buffer
416 * is backed by an array and is not read-only
417 *
418 * @since 1.6
419 */
420 public abstract boolean hasArray();
421
422 /**
423 * Returns the array that backs this
424 * buffer <i>(optional operation)</i>.
425 *
426 * <p> This method is intended to allow array-backed buffers to be
427 * passed to native code more efficiently. Concrete subclasses
428 * provide more strongly-typed return values for this method.
429 *
430 * <p> Modifications to this buffer's content will cause the returned
431 * array's content to be modified, and vice versa.
432 *
433 * <p> Invoke the {@link #hasArray hasArray} method before invoking this
434 * method in order to ensure that this buffer has an accessible backing
435 * array. </p>
436 *
437 * @return The array that backs this buffer
438 *
439 * @throws ReadOnlyBufferException
440 * If this buffer is backed by an array but is read-only
441 *
442 * @throws UnsupportedOperationException
443 * If this buffer is not backed by an accessible array
444 *
445 * @since 1.6
446 */
447 public abstract Object array();
448
449 /**
450 * Returns the offset within this buffer's backing array of the first
451 * element of the buffer <i>(optional operation)</i>.
452 *
453 * <p> If this buffer is backed by an array then buffer position <i>p</i>
454 * corresponds to array index <i>p</i> + <tt>arrayOffset()</tt>.
455 *
456 * <p> Invoke the {@link #hasArray hasArray} method before invoking this
457 * method in order to ensure that this buffer has an accessible backing
458 * array. </p>
459 *
460 * @return The offset within this buffer's array
461 * of the first element of the buffer
462 *
463 * @throws ReadOnlyBufferException
464 * If this buffer is backed by an array but is read-only
465 *
466 * @throws UnsupportedOperationException
467 * If this buffer is not backed by an accessible array
468 *
469 * @since 1.6
470 */
471 public abstract int arrayOffset();
472
473 /**
474 * Tells whether or not this buffer is
475 * <a href="ByteBuffer.html#direct"><i>direct</i></a>. </p>
476 *
477 * @return <tt>true</tt> if, and only if, this buffer is direct
478 *
479 * @since 1.6
480 */
481 public abstract boolean isDirect();
482
483 // -- Package-private methods for bounds checking, etc. --
484
485 /**
486 * Checks the current position against the limit, throwing a {@link
487 * BufferUnderflowException} if it is not smaller than the limit, and then
488 * increments the position. </p>
489 *
490 * @return The current position value, before it is incremented
491 */
492 final int nextGetIndex() { // package-private
493 if (position >= limit)
494 throw new BufferUnderflowException();
495 return position++;
496 }
497
498 final int nextGetIndex(int nb) { // package-private
499 if (limit - position < nb)
500 throw new BufferUnderflowException();
501 int p = position;
502 position += nb;
503 return p;
504 }
505
506 /**
507 * Checks the current position against the limit, throwing a {@link
508 * BufferOverflowException} if it is not smaller than the limit, and then
509 * increments the position. </p>
510 *
511 * @return The current position value, before it is incremented
512 */
513 final int nextPutIndex() { // package-private
514 if (position >= limit)
515 throw new BufferOverflowException();
516 return position++;
517 }
518
519 final int nextPutIndex(int nb) { // package-private
520 if (limit - position < nb)
521 throw new BufferOverflowException();
522 int p = position;
523 position += nb;
524 return p;
525 }
526
527 /**
528 * Checks the given index against the limit, throwing an {@link
529 * IndexOutOfBoundsException} if it is not smaller than the limit
530 * or is smaller than zero.
531 */
532 final int checkIndex(int i) { // package-private
533 if ((i < 0) || (i >= limit))
534 throw new IndexOutOfBoundsException();
535 return i;
536 }
537
538 final int checkIndex(int i, int nb) { // package-private
539 if ((i < 0) || (nb > limit - i))
540 throw new IndexOutOfBoundsException();
541 return i;
542 }
543
544 final int markValue() { // package-private
545 return mark;
546 }
547
548 static void checkBounds(int off, int len, int size) { // package-private
549 if ((off | len | (off + len) | (size - (off + len))) < 0)
550 throw new IndexOutOfBoundsException();
551 }
552
553 }
|