1 /*
   2  * Copyright (c) 2000, 2015, 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 
  30 /**
  31  * A container for data of a specific primitive type.
  32  *
  33  * <p> A buffer is a linear, finite sequence of elements of a specific
  34  * primitive type.  Aside from its content, the essential properties of a
  35  * buffer are its capacity, limit, and position: </p>
  36  *
  37  * <blockquote>
  38  *
  39  *   <p> A buffer's <i>capacity</i> is the number of elements it contains.  The
  40  *   capacity of a buffer is never negative and never changes.  </p>
  41  *
  42  *   <p> A buffer's <i>limit</i> is the index of the first element that should
  43  *   not be read or written.  A buffer's limit is never negative and is never
  44  *   greater than its capacity.  </p>
  45  *
  46  *   <p> A buffer's <i>position</i> is the index of the next element to be
  47  *   read or written.  A buffer's position is never negative and is never
  48  *   greater than its limit.  </p>
  49  *
  50  * </blockquote>
  51  *
  52  * <p> There is one subclass of this class for each non-boolean primitive type.
  53  *
  54  *
  55  * <h2> Transferring data </h2>
  56  *
  57  * <p> Each subclass of this class defines two categories of <i>get</i> and
  58  * <i>put</i> operations: </p>
  59  *
  60  * <blockquote>
  61  *
  62  *   <p> <i>Relative</i> operations read or write one or more elements starting
  63  *   at the current position and then increment the position by the number of
  64  *   elements transferred.  If the requested transfer exceeds the limit then a
  65  *   relative <i>get</i> operation throws a {@link BufferUnderflowException}
  66  *   and a relative <i>put</i> operation throws a {@link
  67  *   BufferOverflowException}; in either case, no data is transferred.  </p>
  68  *
  69  *   <p> <i>Absolute</i> operations take an explicit element index and do not
  70  *   affect the position.  Absolute <i>get</i> and <i>put</i> operations throw
  71  *   an {@link IndexOutOfBoundsException} if the index argument exceeds the
  72  *   limit.  </p>
  73  *
  74  * </blockquote>
  75  *
  76  * <p> Data may also, of course, be transferred in to or out of a buffer by the
  77  * I/O operations of an appropriate channel, which are always relative to the
  78  * current position.
  79  *
  80  *
  81  * <h2> Marking and resetting </h2>
  82  *
  83  * <p> A buffer's <i>mark</i> is the index to which its position will be reset
  84  * when the {@link #reset reset} method is invoked.  The mark is not always
  85  * defined, but when it is defined it is never negative and is never greater
  86  * than the position.  If the mark is defined then it is discarded when the
  87  * position or the limit is adjusted to a value smaller than the mark.  If the
  88  * mark is not defined then invoking the {@link #reset reset} method causes an
  89  * {@link InvalidMarkException} to be thrown.
  90  *
  91  *
  92  * <h2> Invariants </h2>
  93  *
  94  * <p> The following invariant holds for the mark, position, limit, and
  95  * capacity values:
  96  *
  97  * <blockquote>
  98  *     <tt>0</tt> <tt>&lt;=</tt>
  99  *     <i>mark</i> <tt>&lt;=</tt>
 100  *     <i>position</i> <tt>&lt;=</tt>
 101  *     <i>limit</i> <tt>&lt;=</tt>
 102  *     <i>capacity</i>
 103  * </blockquote>
 104  *
 105  * <p> A newly-created buffer always has a position of zero and a mark that is
 106  * undefined.  The initial limit may be zero, or it may be some other value
 107  * that depends upon the type of the buffer and the manner in which it is
 108  * constructed.  Each element of a newly-allocated buffer is initialized
 109  * to zero.
 110  *
 111  *
 112  * <h2> Clearing, flipping, and rewinding </h2>
 113  *
 114  * <p> In addition to methods for accessing the position, limit, and capacity
 115  * values and for marking and resetting, this class also defines the following
 116  * operations upon buffers:
 117  *
 118  * <ul>
 119  *
 120  *   <li><p> {@link #clear} makes a buffer ready for a new sequence of
 121  *   channel-read or relative <i>put</i> operations: It sets the limit to the
 122  *   capacity and the position to zero.  </p></li>
 123  *
 124  *   <li><p> {@link #flip} makes a buffer ready for a new sequence of
 125  *   channel-write or relative <i>get</i> operations: It sets the limit to the
 126  *   current position and then sets the position to zero.  </p></li>
 127  *
 128  *   <li><p> {@link #rewind} makes a buffer ready for re-reading the data that
 129  *   it already contains: It leaves the limit unchanged and sets the position
 130  *   to zero.  </p></li>
 131  *
 132  * </ul>
 133  *
 134  *
 135  * <h2> Read-only buffers </h2>
 136  *
 137  * <p> Every buffer is readable, but not every buffer is writable.  The
 138  * mutation methods of each buffer class are specified as <i>optional
 139  * operations</i> that will throw a {@link ReadOnlyBufferException} when
 140  * invoked upon a read-only buffer.  A read-only buffer does not allow its
 141  * content to be changed, but its mark, position, and limit values are mutable.
 142  * Whether or not a buffer is read-only may be determined by invoking its
 143  * {@link #isReadOnly isReadOnly} method.
 144  *
 145  *
 146  * <h2> Thread safety </h2>
 147  *
 148  * <p> Buffers are not safe for use by multiple concurrent threads.  If a
 149  * buffer is to be used by more than one thread then access to the buffer
 150  * should be controlled by appropriate synchronization.
 151  *
 152  *
 153  * <h2> Invocation chaining </h2>
 154  *
 155  * <p> Methods in this class that do not otherwise have a value to return are
 156  * specified to return the buffer upon which they are invoked.  This allows
 157  * method invocations to be chained; for example, the sequence of statements
 158  *
 159  * <blockquote><pre>
 160  * b.flip();
 161  * b.position(23);
 162  * b.limit(42);</pre></blockquote>
 163  *
 164  * can be replaced by the single, more compact statement
 165  *
 166  * <blockquote><pre>
 167  * b.flip().position(23).limit(42);</pre></blockquote>
 168  *
 169  *
 170  * @author Mark Reinhold
 171  * @author JSR-51 Expert Group
 172  * @since 1.4
 173  */
 174 
 175 public abstract class Buffer {
 176 
 177     /**
 178      * The characteristics of Spliterators that traverse and split elements
 179      * maintained in Buffers.
 180      */
 181     static final int SPLITERATOR_CHARACTERISTICS =
 182         Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED;
 183 
 184     // Invariants: mark <= position <= limit <= capacity
 185     private int mark = -1;
 186     private int position = 0;
 187     private int limit;
 188     private int capacity;
 189 
 190     // Used only by direct buffers
 191     // NOTE: hoisted here for speed in JNI GetDirectBufferAddress
 192     long address;
 193 
 194     // Creates a new buffer with the given mark, position, limit, and capacity,
 195     // after checking invariants.
 196     //
 197     Buffer(int mark, int pos, int lim, int cap) {       // package-private
 198         if (cap < 0) {
 199             throw negativeCapacityException(cap);
 200         }
 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 positionOutOfBoundsException(newPosition);
 246         }
 247         position = newPosition;
 248         if (mark > position) mark = -1;
 249         return this;
 250     }
 251 
 252     /**
 253      * Verify that {@code 0 < newPosition <= limit}
 254      *
 255      * @param newPosition
 256      *        The new position value
 257      *
 258      * @throws IllegalArgumentException
 259      *         If the specified position is out of bounds.
 260      */
 261     private IllegalArgumentException positionOutOfBoundsException(int newPosition) {
 262         String msg = null;
 263 
 264         if (newPosition > limit) {
 265             msg = "newPosition > limit: (" + newPosition + " > " + limit + ")";
 266         } else { // assume negative
 267             assert newPosition < 0 : "newPosition expected to be negative";
 268             msg = "newPosition < 0: (" + newPosition + " < 0)";
 269         }
 270 
 271         return new IllegalArgumentException(msg);
 272     }
 273 
 274     /**
 275      * Returns this buffer's limit.
 276      *
 277      * @return  The limit of this buffer
 278      */
 279     public final int limit() {
 280         return limit;
 281     }
 282 
 283     /**
 284      * Sets this buffer's limit.  If the position is larger than the new limit
 285      * then it is set to the new limit.  If the mark is defined and larger than
 286      * the new limit then it is discarded.
 287      *
 288      * @param  newLimit
 289      *         The new limit value; must be non-negative
 290      *         and no larger than this buffer's capacity
 291      *
 292      * @return  This buffer
 293      *
 294      * @throws  IllegalArgumentException
 295      *          If the preconditions on <tt>newLimit</tt> do not hold
 296      */
 297     public Buffer limit(int newLimit) {
 298         if (newLimit > capacity || newLimit < 0) {
 299             throw limitOutOfBoundsException(newLimit);
 300         }
 301         limit = newLimit;
 302         if (position > limit) position = limit;
 303         if (mark > limit) mark = -1;
 304         return this;
 305     }
 306 
 307     /**
 308      * Verify that {@code 0 < newLimit <= capacity}
 309      *
 310      * @param newLimit
 311      *        The new limit value
 312      *
 313      * @throws IllegalArgumentException
 314      *         If the specified limit is out of bounds.
 315      */
 316     private IllegalArgumentException limitOutOfBoundsException(int newLimit) {
 317         String msg = null;
 318 
 319         if (newLimit > capacity) {
 320             msg = "newLimit > capacity: (" + newLimit + " > " + capacity + ")";
 321         } else { // assume negative
 322             assert newLimit < 0 : "newLimit expected to be negative";
 323             msg = "newLimit < 0: (" + newLimit + " < 0)";
 324         }
 325 
 326         return new IllegalArgumentException(msg);
 327     }
 328 
 329     /**
 330      * Sets this buffer's mark at its position.
 331      *
 332      * @return  This buffer
 333      */
 334     public Buffer mark() {
 335         mark = position;
 336         return this;
 337     }
 338 
 339     /**
 340      * Resets this buffer's position to the previously-marked position.
 341      *
 342      * <p> Invoking this method neither changes nor discards the mark's
 343      * value. </p>
 344      *
 345      * @return  This buffer
 346      *
 347      * @throws  InvalidMarkException
 348      *          If the mark has not been set
 349      */
 350     public Buffer reset() {
 351         int m = mark;
 352         if (m < 0)
 353             throw new InvalidMarkException();
 354         position = m;
 355         return this;
 356     }
 357 
 358     /**
 359      * Clears this buffer.  The position is set to zero, the limit is set to
 360      * the capacity, and the mark is discarded.
 361      *
 362      * <p> Invoke this method before using a sequence of channel-read or
 363      * <i>put</i> operations to fill this buffer.  For example:
 364      *
 365      * <blockquote><pre>
 366      * buf.clear();     // Prepare buffer for reading
 367      * in.read(buf);    // Read data</pre></blockquote>
 368      *
 369      * <p> This method does not actually erase the data in the buffer, but it
 370      * is named as if it did because it will most often be used in situations
 371      * in which that might as well be the case. </p>
 372      *
 373      * @return  This buffer
 374      */
 375     public Buffer clear() {
 376         position = 0;
 377         limit = capacity;
 378         mark = -1;
 379         return this;
 380     }
 381 
 382     /**
 383      * Flips this buffer.  The limit is set to the current position and then
 384      * the position is set to zero.  If the mark is defined then it is
 385      * discarded.
 386      *
 387      * <p> After a sequence of channel-read or <i>put</i> operations, invoke
 388      * this method to prepare for a sequence of channel-write or relative
 389      * <i>get</i> operations.  For example:
 390      *
 391      * <blockquote><pre>
 392      * buf.put(magic);    // Prepend header
 393      * in.read(buf);      // Read data into rest of buffer
 394      * buf.flip();        // Flip buffer
 395      * out.write(buf);    // Write header + data to channel</pre></blockquote>
 396      *
 397      * <p> This method is often used in conjunction with the {@link
 398      * java.nio.ByteBuffer#compact compact} method when transferring data from
 399      * one place to another.  </p>
 400      *
 401      * @return  This buffer
 402      */
 403     public Buffer flip() {
 404         limit = position;
 405         position = 0;
 406         mark = -1;
 407         return this;
 408     }
 409 
 410     /**
 411      * Rewinds this buffer.  The position is set to zero and the mark is
 412      * discarded.
 413      *
 414      * <p> Invoke this method before a sequence of channel-write or <i>get</i>
 415      * operations, assuming that the limit has already been set
 416      * appropriately.  For example:
 417      *
 418      * <blockquote><pre>
 419      * out.write(buf);    // Write remaining data
 420      * buf.rewind();      // Rewind buffer
 421      * buf.get(array);    // Copy data into array</pre></blockquote>
 422      *
 423      * @return  This buffer
 424      */
 425     public Buffer rewind() {
 426         position = 0;
 427         mark = -1;
 428         return this;
 429     }
 430 
 431     /**
 432      * Returns the number of elements between the current position and the
 433      * limit.
 434      *
 435      * @return  The number of elements remaining in this buffer
 436      */
 437     public final int remaining() {
 438         return limit - position;
 439     }
 440 
 441     /**
 442      * Tells whether there are any elements between the current position and
 443      * the limit.
 444      *
 445      * @return  <tt>true</tt> if, and only if, there is at least one element
 446      *          remaining in this buffer
 447      */
 448     public final boolean hasRemaining() {
 449         return position < limit;
 450     }
 451 
 452     /**
 453      * Tells whether or not this buffer is read-only.
 454      *
 455      * @return  <tt>true</tt> if, and only if, this buffer is read-only
 456      */
 457     public abstract boolean isReadOnly();
 458 
 459     /**
 460      * Tells whether or not this buffer is backed by an accessible
 461      * array.
 462      *
 463      * <p> If this method returns <tt>true</tt> then the {@link #array() array}
 464      * and {@link #arrayOffset() arrayOffset} methods may safely be invoked.
 465      * </p>
 466      *
 467      * @return  <tt>true</tt> if, and only if, this buffer
 468      *          is backed by an array and is not read-only
 469      *
 470      * @since 1.6
 471      */
 472     public abstract boolean hasArray();
 473 
 474     /**
 475      * Returns the array that backs this
 476      * buffer&nbsp;&nbsp;<i>(optional operation)</i>.
 477      *
 478      * <p> This method is intended to allow array-backed buffers to be
 479      * passed to native code more efficiently. Concrete subclasses
 480      * provide more strongly-typed return values for this method.
 481      *
 482      * <p> Modifications to this buffer's content will cause the returned
 483      * array's content to be modified, and vice versa.
 484      *
 485      * <p> Invoke the {@link #hasArray hasArray} method before invoking this
 486      * method in order to ensure that this buffer has an accessible backing
 487      * array.  </p>
 488      *
 489      * @return  The array that backs this buffer
 490      *
 491      * @throws  ReadOnlyBufferException
 492      *          If this buffer is backed by an array but is read-only
 493      *
 494      * @throws  UnsupportedOperationException
 495      *          If this buffer is not backed by an accessible array
 496      *
 497      * @since 1.6
 498      */
 499     public abstract Object array();
 500 
 501     /**
 502      * Returns the offset within this buffer's backing array of the first
 503      * element of the buffer&nbsp;&nbsp;<i>(optional operation)</i>.
 504      *
 505      * <p> If this buffer is backed by an array then buffer position <i>p</i>
 506      * corresponds to array index <i>p</i>&nbsp;+&nbsp;<tt>arrayOffset()</tt>.
 507      *
 508      * <p> Invoke the {@link #hasArray hasArray} method before invoking this
 509      * method in order to ensure that this buffer has an accessible backing
 510      * array.  </p>
 511      *
 512      * @return  The offset within this buffer's array
 513      *          of the first element of the buffer
 514      *
 515      * @throws  ReadOnlyBufferException
 516      *          If this buffer is backed by an array but is read-only
 517      *
 518      * @throws  UnsupportedOperationException
 519      *          If this buffer is not backed by an accessible array
 520      *
 521      * @since 1.6
 522      */
 523     public abstract int arrayOffset();
 524 
 525     /**
 526      * Tells whether or not this buffer is
 527      * <a href="ByteBuffer.html#direct"><i>direct</i></a>.
 528      *
 529      * @return  <tt>true</tt> if, and only if, this buffer is direct
 530      *
 531      * @since 1.6
 532      */
 533     public abstract boolean isDirect();
 534 
 535     // -- Package-private methods for bounds checking, etc. --
 536 
 537     /**
 538      * Checks the current position against the limit, throwing a {@link
 539      * BufferUnderflowException} if it is not smaller than the limit, and then
 540      * increments the position.
 541      *
 542      * @return  The current position value, before it is incremented
 543      */
 544     final int nextGetIndex() {                          // package-private
 545         if (position >= limit)
 546             throw new BufferUnderflowException();
 547         return position++;
 548     }
 549 
 550     final int nextGetIndex(int nb) {                    // package-private
 551         if (limit - position < nb)
 552             throw new BufferUnderflowException();
 553         int p = position;
 554         position += nb;
 555         return p;
 556     }
 557 
 558     /**
 559      * Checks the current position against the limit, throwing a {@link
 560      * BufferOverflowException} if it is not smaller than the limit, and then
 561      * increments the position.
 562      *
 563      * @return  The current position value, before it is incremented
 564      */
 565     final int nextPutIndex() {                          // package-private
 566         if (position >= limit)
 567             throw new BufferOverflowException();
 568         return position++;
 569     }
 570 
 571     final int nextPutIndex(int nb) {                    // package-private
 572         if (limit - position < nb)
 573             throw new BufferOverflowException();
 574         int p = position;
 575         position += nb;
 576         return p;
 577     }
 578 
 579     /**
 580      * Checks the given index against the limit, throwing an {@link
 581      * IndexOutOfBoundsException} if it is not smaller than the limit
 582      * or is smaller than zero.
 583      */
 584     final int checkIndex(int i) {                       // package-private
 585         if ((i < 0) || (i >= limit))
 586             throw new IndexOutOfBoundsException();
 587         return i;
 588     }
 589 
 590     final int checkIndex(int i, int nb) {               // package-private
 591         if ((i < 0) || (nb > limit - i))
 592             throw new IndexOutOfBoundsException();
 593         return i;
 594     }
 595 
 596     final int markValue() {                             // package-private
 597         return mark;
 598     }
 599 
 600     final void truncate() {                             // package-private
 601         mark = -1;
 602         position = 0;
 603         limit = 0;
 604         capacity = 0;
 605     }
 606 
 607     final void discardMark() {                          // package-private
 608         mark = -1;
 609     }
 610 
 611     static void checkBounds(int off, int len, int size) { // package-private
 612         if ((off | len | (off + len) | (size - (off + len))) < 0)
 613             throw new IndexOutOfBoundsException();
 614     }
 615 
 616     /**
 617      * Verify that the parameter is not this {@code Buffer}.  Intended for
 618      * checking that in {@code put(src)} the parameter is not the {@code Buffer}
 619      * on which the method is being invoked.
 620      *
 621      * @param src
 622      *        The buffer to compare with.
 623      *
 624      * @throws  IllegalArgumentException
 625      *          If the source buffer is this buffer
 626      */
 627     void checkSourceBufferNotThisBuffer(Buffer src) {   // package-private
 628         if (src == this) {
 629             throw new IllegalArgumentException("The source buffer is this buffer");
 630         }
 631     }
 632 
 633     /**
 634      * Verify that the capacity is nonnegative.
 635      *
 636      * @param  capacity
 637      *         The new buffer's capacity, in $type$s
 638      *
 639      * @throws  IllegalArgumentException
 640      *          If the <tt>capacity</tt> is a negative integer
 641      */
 642     static IllegalArgumentException negativeCapacityException(int capacity) { // package-private
 643         assert capacity < 0 : "capacity expected to be negative";
 644         return new IllegalArgumentException("capacity < 0: ("
 645             + capacity + " < 0)");
 646     }
 647 }