1 /*
   2  * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.nio;
  27 
  28 import java.util.Spliterator;
  29 import jdk.internal.HotSpotIntrinsicCandidate;
  30 
  31 /**
  32  * A container for data of a specific primitive type.
  33  *
  34  * <p> A buffer is a linear, finite sequence of elements of a specific
  35  * primitive type.  Aside from its content, the essential properties of a
  36  * buffer are its capacity, limit, and position: </p>
  37  *
  38  * <blockquote>
  39  *
  40  *   <p> A buffer's <i>capacity</i> is the number of elements it contains.  The
  41  *   capacity of a buffer is never negative and never changes.  </p>
  42  *
  43  *   <p> A buffer's <i>limit</i> is the index of the first element that should
  44  *   not be read or written.  A buffer's limit is never negative and is never
  45  *   greater than its capacity.  </p>
  46  *
  47  *   <p> A buffer's <i>position</i> is the index of the next element to be
  48  *   read or written.  A buffer's position is never negative and is never
  49  *   greater than its limit.  </p>
  50  *
  51  * </blockquote>
  52  *
  53  * <p> There is one subclass of this class for each non-boolean primitive type.
  54  *
  55  *
  56  * <h2> Transferring data </h2>
  57  *
  58  * <p> Each subclass of this class defines two categories of <i>get</i> and
  59  * <i>put</i> operations: </p>
  60  *
  61  * <blockquote>
  62  *
  63  *   <p> <i>Relative</i> operations read or write one or more elements starting
  64  *   at the current position and then increment the position by the number of
  65  *   elements transferred.  If the requested transfer exceeds the limit then a
  66  *   relative <i>get</i> operation throws a {@link BufferUnderflowException}
  67  *   and a relative <i>put</i> operation throws a {@link
  68  *   BufferOverflowException}; in either case, no data is transferred.  </p>
  69  *
  70  *   <p> <i>Absolute</i> operations take an explicit element index and do not
  71  *   affect the position.  Absolute <i>get</i> and <i>put</i> operations throw
  72  *   an {@link IndexOutOfBoundsException} if the index argument exceeds the
  73  *   limit.  </p>
  74  *
  75  * </blockquote>
  76  *
  77  * <p> Data may also, of course, be transferred in to or out of a buffer by the
  78  * I/O operations of an appropriate channel, which are always relative to the
  79  * current position.
  80  *
  81  *
  82  * <h2> Marking and resetting </h2>
  83  *
  84  * <p> A buffer's <i>mark</i> is the index to which its position will be reset
  85  * when the {@link #reset reset} method is invoked.  The mark is not always
  86  * defined, but when it is defined it is never negative and is never greater
  87  * than the position.  If the mark is defined then it is discarded when the
  88  * position or the limit is adjusted to a value smaller than the mark.  If the
  89  * mark is not defined then invoking the {@link #reset reset} method causes an
  90  * {@link InvalidMarkException} to be thrown.
  91  *
  92  *
  93  * <h2> Invariants </h2>
  94  *
  95  * <p> The following invariant holds for the mark, position, limit, and
  96  * capacity values:
  97  *
  98  * <blockquote>
  99  *     <tt>0</tt> <tt>&lt;=</tt>
 100  *     <i>mark</i> <tt>&lt;=</tt>
 101  *     <i>position</i> <tt>&lt;=</tt>
 102  *     <i>limit</i> <tt>&lt;=</tt>
 103  *     <i>capacity</i>
 104  * </blockquote>
 105  *
 106  * <p> A newly-created buffer always has a position of zero and a mark that is
 107  * undefined.  The initial limit may be zero, or it may be some other value
 108  * that depends upon the type of the buffer and the manner in which it is
 109  * constructed.  Each element of a newly-allocated buffer is initialized
 110  * to zero.
 111  *
 112  *
 113  * <h2> Clearing, flipping, and rewinding </h2>
 114  *
 115  * <p> In addition to methods for accessing the position, limit, and capacity
 116  * values and for marking and resetting, this class also defines the following
 117  * operations upon buffers:
 118  *
 119  * <ul>
 120  *
 121  *   <li><p> {@link #clear} makes a buffer ready for a new sequence of
 122  *   channel-read or relative <i>put</i> operations: It sets the limit to the
 123  *   capacity and the position to zero.  </p></li>
 124  *
 125  *   <li><p> {@link #flip} makes a buffer ready for a new sequence of
 126  *   channel-write or relative <i>get</i> operations: It sets the limit to the
 127  *   current position and then sets the position to zero.  </p></li>
 128  *
 129  *   <li><p> {@link #rewind} makes a buffer ready for re-reading the data that
 130  *   it already contains: It leaves the limit unchanged and sets the position
 131  *   to zero.  </p></li>
 132  *
 133  * </ul>
 134  *
 135  *
 136  * <h2> Read-only buffers </h2>
 137  *
 138  * <p> Every buffer is readable, but not every buffer is writable.  The
 139  * mutation methods of each buffer class are specified as <i>optional
 140  * operations</i> that will throw a {@link ReadOnlyBufferException} when
 141  * invoked upon a read-only buffer.  A read-only buffer does not allow its
 142  * content to be changed, but its mark, position, and limit values are mutable.
 143  * Whether or not a buffer is read-only may be determined by invoking its
 144  * {@link #isReadOnly isReadOnly} method.
 145  *
 146  *
 147  * <h2> Thread safety </h2>
 148  *
 149  * <p> Buffers are not safe for use by multiple concurrent threads.  If a
 150  * buffer is to be used by more than one thread then access to the buffer
 151  * should be controlled by appropriate synchronization.
 152  *
 153  *
 154  * <h2> Invocation chaining </h2>
 155  *
 156  * <p> Methods in this class that do not otherwise have a value to return are
 157  * specified to return the buffer upon which they are invoked.  This allows
 158  * method invocations to be chained; for example, the sequence of statements
 159  *
 160  * <blockquote><pre>
 161  * b.flip();
 162  * b.position(23);
 163  * b.limit(42);</pre></blockquote>
 164  *
 165  * can be replaced by the single, more compact statement
 166  *
 167  * <blockquote><pre>
 168  * b.flip().position(23).limit(42);</pre></blockquote>
 169  *
 170  *
 171  * @author Mark Reinhold
 172  * @author JSR-51 Expert Group
 173  * @since 1.4
 174  */
 175 
 176 public abstract class Buffer {
 177 
 178     /**
 179      * The characteristics of Spliterators that traverse and split elements
 180      * maintained in Buffers.
 181      */
 182     static final int SPLITERATOR_CHARACTERISTICS =
 183         Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED;
 184 
 185     // Invariants: mark <= position <= limit <= capacity
 186     private int mark = -1;
 187     private int position = 0;
 188     private int limit;
 189     private int capacity;
 190 
 191     // Used only by direct buffers
 192     // NOTE: hoisted here for speed in JNI GetDirectBufferAddress
 193     long address;
 194 
 195     // Creates a new buffer with the given mark, position, limit, and capacity,
 196     // after checking invariants.
 197     //
 198     Buffer(int mark, int pos, int lim, int cap) {       // package-private
 199         if (cap < 0)
 200             throw new IllegalArgumentException("Negative capacity: " + cap);
 201         this.capacity = cap;
 202         limit(lim);
 203         position(pos);
 204         if (mark >= 0) {
 205             if (mark > pos)
 206                 throw new IllegalArgumentException("mark > position: ("
 207                                                    + mark + " > " + pos + ")");
 208             this.mark = mark;
 209         }
 210     }
 211 
 212     /**
 213      * Returns this buffer's capacity.
 214      *
 215      * @return  The capacity of this buffer
 216      */
 217     public final int capacity() {
 218         return capacity;
 219     }
 220 
 221     /**
 222      * Returns this buffer's position.
 223      *
 224      * @return  The position of this buffer
 225      */
 226     public final int position() {
 227         return position;
 228     }
 229 
 230     /**
 231      * Sets this buffer's position.  If the mark is defined and larger than the
 232      * new position then it is discarded.
 233      *
 234      * @param  newPosition
 235      *         The new position value; must be non-negative
 236      *         and no larger than the current limit
 237      *
 238      * @return  This buffer
 239      *
 240      * @throws  IllegalArgumentException
 241      *          If the preconditions on <tt>newPosition</tt> do not hold
 242      */
 243     public Buffer position(int newPosition) {
 244         if ((newPosition > limit) || (newPosition < 0))
 245             throw new IllegalArgumentException();
 246         position = newPosition;
 247         if (mark > position) mark = -1;
 248         return this;
 249     }
 250 
 251     /**
 252      * Returns this buffer's limit.
 253      *
 254      * @return  The limit of this buffer
 255      */
 256     public final int limit() {
 257         return limit;
 258     }
 259 
 260     /**
 261      * Sets this buffer's limit.  If the position is larger than the new limit
 262      * then it is set to the new limit.  If the mark is defined and larger than
 263      * the new limit then it is discarded.
 264      *
 265      * @param  newLimit
 266      *         The new limit value; must be non-negative
 267      *         and no larger than this buffer's capacity
 268      *
 269      * @return  This buffer
 270      *
 271      * @throws  IllegalArgumentException
 272      *          If the preconditions on <tt>newLimit</tt> do not hold
 273      */
 274     public Buffer limit(int newLimit) {
 275         if ((newLimit > capacity) || (newLimit < 0))
 276             throw new IllegalArgumentException();
 277         limit = newLimit;
 278         if (position > limit) position = limit;
 279         if (mark > limit) mark = -1;
 280         return this;
 281     }
 282 
 283     /**
 284      * Sets this buffer's mark at its position.
 285      *
 286      * @return  This buffer
 287      */
 288     public Buffer mark() {
 289         mark = position;
 290         return this;
 291     }
 292 
 293     /**
 294      * Resets this buffer's position to the previously-marked position.
 295      *
 296      * <p> Invoking this method neither changes nor discards the mark's
 297      * value. </p>
 298      *
 299      * @return  This buffer
 300      *
 301      * @throws  InvalidMarkException
 302      *          If the mark has not been set
 303      */
 304     public Buffer reset() {
 305         int m = mark;
 306         if (m < 0)
 307             throw new InvalidMarkException();
 308         position = m;
 309         return this;
 310     }
 311 
 312     /**
 313      * Clears this buffer.  The position is set to zero, the limit is set to
 314      * the capacity, and the mark is discarded.
 315      *
 316      * <p> Invoke this method before using a sequence of channel-read or
 317      * <i>put</i> operations to fill this buffer.  For example:
 318      *
 319      * <blockquote><pre>
 320      * buf.clear();     // Prepare buffer for reading
 321      * in.read(buf);    // Read data</pre></blockquote>
 322      *
 323      * <p> This method does not actually erase the data in the buffer, but it
 324      * is named as if it did because it will most often be used in situations
 325      * in which that might as well be the case. </p>
 326      *
 327      * @return  This buffer
 328      */
 329     public Buffer clear() {
 330         position = 0;
 331         limit = capacity;
 332         mark = -1;
 333         return this;
 334     }
 335 
 336     /**
 337      * Flips this buffer.  The limit is set to the current position and then
 338      * the position is set to zero.  If the mark is defined then it is
 339      * discarded.
 340      *
 341      * <p> After a sequence of channel-read or <i>put</i> operations, invoke
 342      * this method to prepare for a sequence of channel-write or relative
 343      * <i>get</i> operations.  For example:
 344      *
 345      * <blockquote><pre>
 346      * buf.put(magic);    // Prepend header
 347      * in.read(buf);      // Read data into rest of buffer
 348      * buf.flip();        // Flip buffer
 349      * out.write(buf);    // Write header + data to channel</pre></blockquote>
 350      *
 351      * <p> This method is often used in conjunction with the {@link
 352      * java.nio.ByteBuffer#compact compact} method when transferring data from
 353      * one place to another.  </p>
 354      *
 355      * @return  This buffer
 356      */
 357     public Buffer flip() {
 358         limit = position;
 359         position = 0;
 360         mark = -1;
 361         return this;
 362     }
 363 
 364     /**
 365      * Rewinds this buffer.  The position is set to zero and the mark is
 366      * discarded.
 367      *
 368      * <p> Invoke this method before a sequence of channel-write or <i>get</i>
 369      * operations, assuming that the limit has already been set
 370      * appropriately.  For example:
 371      *
 372      * <blockquote><pre>
 373      * out.write(buf);    // Write remaining data
 374      * buf.rewind();      // Rewind buffer
 375      * buf.get(array);    // Copy data into array</pre></blockquote>
 376      *
 377      * @return  This buffer
 378      */
 379     public Buffer rewind() {
 380         position = 0;
 381         mark = -1;
 382         return this;
 383     }
 384 
 385     /**
 386      * Returns the number of elements between the current position and the
 387      * limit.
 388      *
 389      * @return  The number of elements remaining in this buffer
 390      */
 391     public final int remaining() {
 392         return limit - position;
 393     }
 394 
 395     /**
 396      * Tells whether there are any elements between the current position and
 397      * the limit.
 398      *
 399      * @return  <tt>true</tt> if, and only if, there is at least one element
 400      *          remaining in this buffer
 401      */
 402     public final boolean hasRemaining() {
 403         return position < limit;
 404     }
 405 
 406     /**
 407      * Tells whether or not this buffer is read-only.
 408      *
 409      * @return  <tt>true</tt> if, and only if, this buffer is read-only
 410      */
 411     public abstract boolean isReadOnly();
 412 
 413     /**
 414      * Tells whether or not this buffer is backed by an accessible
 415      * array.
 416      *
 417      * <p> If this method returns <tt>true</tt> then the {@link #array() array}
 418      * and {@link #arrayOffset() arrayOffset} methods may safely be invoked.
 419      * </p>
 420      *
 421      * @return  <tt>true</tt> if, and only if, this buffer
 422      *          is backed by an array and is not read-only
 423      *
 424      * @since 1.6
 425      */
 426     public abstract boolean hasArray();
 427 
 428     /**
 429      * Returns the array that backs this
 430      * buffer&nbsp;&nbsp;<i>(optional operation)</i>.
 431      *
 432      * <p> This method is intended to allow array-backed buffers to be
 433      * passed to native code more efficiently. Concrete subclasses
 434      * provide more strongly-typed return values for this method.
 435      *
 436      * <p> Modifications to this buffer's content will cause the returned
 437      * array's content to be modified, and vice versa.
 438      *
 439      * <p> Invoke the {@link #hasArray hasArray} method before invoking this
 440      * method in order to ensure that this buffer has an accessible backing
 441      * array.  </p>
 442      *
 443      * @return  The array that backs this buffer
 444      *
 445      * @throws  ReadOnlyBufferException
 446      *          If this buffer is backed by an array but is read-only
 447      *
 448      * @throws  UnsupportedOperationException
 449      *          If this buffer is not backed by an accessible array
 450      *
 451      * @since 1.6
 452      */
 453     public abstract Object array();
 454 
 455     /**
 456      * Returns the offset within this buffer's backing array of the first
 457      * element of the buffer&nbsp;&nbsp;<i>(optional operation)</i>.
 458      *
 459      * <p> If this buffer is backed by an array then buffer position <i>p</i>
 460      * corresponds to array index <i>p</i>&nbsp;+&nbsp;<tt>arrayOffset()</tt>.
 461      *
 462      * <p> Invoke the {@link #hasArray hasArray} method before invoking this
 463      * method in order to ensure that this buffer has an accessible backing
 464      * array.  </p>
 465      *
 466      * @return  The offset within this buffer's array
 467      *          of the first element of the buffer
 468      *
 469      * @throws  ReadOnlyBufferException
 470      *          If this buffer is backed by an array but is read-only
 471      *
 472      * @throws  UnsupportedOperationException
 473      *          If this buffer is not backed by an accessible array
 474      *
 475      * @since 1.6
 476      */
 477     public abstract int arrayOffset();
 478 
 479     /**
 480      * Tells whether or not this buffer is
 481      * <a href="ByteBuffer.html#direct"><i>direct</i></a>.
 482      *
 483      * @return  <tt>true</tt> if, and only if, this buffer is direct
 484      *
 485      * @since 1.6
 486      */
 487     public abstract boolean isDirect();
 488 
 489 
 490     // -- Package-private methods for bounds checking, etc. --
 491 
 492     /**
 493      * Checks the current position against the limit, throwing a {@link
 494      * BufferUnderflowException} if it is not smaller than the limit, and then
 495      * increments the position.
 496      *
 497      * @return  The current position value, before it is incremented
 498      */
 499     final int nextGetIndex() {                          // package-private
 500         if (position >= limit)
 501             throw new BufferUnderflowException();
 502         return position++;
 503     }
 504 
 505     final int nextGetIndex(int nb) {                    // package-private
 506         if (limit - position < nb)
 507             throw new BufferUnderflowException();
 508         int p = position;
 509         position += nb;
 510         return p;
 511     }
 512 
 513     /**
 514      * Checks the current position against the limit, throwing a {@link
 515      * BufferOverflowException} if it is not smaller than the limit, and then
 516      * increments the position.
 517      *
 518      * @return  The current position value, before it is incremented
 519      */
 520     final int nextPutIndex() {                          // package-private
 521         if (position >= limit)
 522             throw new BufferOverflowException();
 523         return position++;
 524     }
 525 
 526     final int nextPutIndex(int nb) {                    // package-private
 527         if (limit - position < nb)
 528             throw new BufferOverflowException();
 529         int p = position;
 530         position += nb;
 531         return p;
 532     }
 533 
 534     /**
 535      * Checks the given index against the limit, throwing an {@link
 536      * IndexOutOfBoundsException} if it is not smaller than the limit
 537      * or is smaller than zero.
 538      */
 539     @HotSpotIntrinsicCandidate
 540     final int checkIndex(int i) {                       // package-private
 541         if ((i < 0) || (i >= limit))
 542             throw new IndexOutOfBoundsException();
 543         return i;
 544     }
 545 
 546     final int checkIndex(int i, int nb) {               // package-private
 547         if ((i < 0) || (nb > limit - i))
 548             throw new IndexOutOfBoundsException();
 549         return i;
 550     }
 551 
 552     final int markValue() {                             // package-private
 553         return mark;
 554     }
 555 
 556     final void truncate() {                             // package-private
 557         mark = -1;
 558         position = 0;
 559         limit = 0;
 560         capacity = 0;
 561     }
 562 
 563     final void discardMark() {                          // package-private
 564         mark = -1;
 565     }
 566 
 567     static void checkBounds(int off, int len, int size) { // package-private
 568         if ((off | len | (off + len) | (size - (off + len))) < 0)
 569             throw new IndexOutOfBoundsException();
 570     }
 571 
 572 }