1 /*
   2  * Copyright (c) 2000, 2016, 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 #warn This file is preprocessed before being compiled
  27 
  28 package java.nio;
  29 
  30 #if[char]
  31 import java.io.IOException;
  32 #end[char]
  33 #if[streamableType]
  34 import java.util.Spliterator;
  35 import java.util.stream.StreamSupport;
  36 import java.util.stream.$Streamtype$Stream;
  37 #end[streamableType]
  38 
  39 /**
  40  * $A$ $type$ buffer.
  41  *
  42  * <p> This class defines {#if[byte]?six:four} categories of operations upon
  43  * $type$ buffers:
  44  *
  45  * <ul>
  46  *
  47  *   <li><p> Absolute and relative {@link #get() <i>get</i>} and
  48  *   {@link #put($type$) <i>put</i>} methods that read and write
  49  *   single $type$s; </p></li>
  50  *
  51  *   <li><p> Relative {@link #get($type$[]) <i>bulk get</i>}
  52  *   methods that transfer contiguous sequences of $type$s from this buffer
  53  *   into an array; {#if[!byte]?and}</p></li>
  54  *
  55  *   <li><p> Relative {@link #put($type$[]) <i>bulk put</i>}
  56  *   methods that transfer contiguous sequences of $type$s from $a$
  57  *   $type$ array{#if[char]?, a string,} or some other $type$
  58  *   buffer into this buffer;{#if[!byte]? and} </p></li>
  59  *
  60 #if[byte]
  61  *
  62  *   <li><p> Absolute and relative {@link #getChar() <i>get</i>}
  63  *   and {@link #putChar(char) <i>put</i>} methods that read and
  64  *   write values of other primitive types, translating them to and from
  65  *   sequences of bytes in a particular byte order; </p></li>
  66  *
  67  *   <li><p> Methods for creating <i><a href="#views">view buffers</a></i>,
  68  *   which allow a byte buffer to be viewed as a buffer containing values of
  69  *   some other primitive type; and </p></li>
  70  *
  71 #end[byte]
  72  *
  73  *   <li><p> A method for {@link #compact compacting}
  74  *   $a$ $type$ buffer.  </p></li>
  75  *
  76  * </ul>
  77  *
  78  * <p> $Type$ buffers can be created either by {@link #allocate
  79  * <i>allocation</i>}, which allocates space for the buffer's
  80  *
  81 #if[byte]
  82  *
  83  * content, or by {@link #wrap($type$[]) <i>wrapping</i>} an
  84  * existing $type$ array {#if[char]?or string} into a buffer.
  85  *
  86 #else[byte]
  87  *
  88  * content, by {@link #wrap($type$[]) <i>wrapping</i>} an existing
  89  * $type$ array {#if[char]?or string} into a buffer, or by creating a
  90  * <a href="ByteBuffer.html#views"><i>view</i></a> of an existing byte buffer.
  91  *
  92 #end[byte]
  93  *
  94 #if[byte]
  95  *
  96  * <a name="direct"></a>
  97  * <h2> Direct <i>vs.</i> non-direct buffers </h2>
  98  *
  99  * <p> A byte buffer is either <i>direct</i> or <i>non-direct</i>.  Given a
 100  * direct byte buffer, the Java virtual machine will make a best effort to
 101  * perform native I/O operations directly upon it.  That is, it will attempt to
 102  * avoid copying the buffer's content to (or from) an intermediate buffer
 103  * before (or after) each invocation of one of the underlying operating
 104  * system's native I/O operations.
 105  *
 106  * <p> A direct byte buffer may be created by invoking the {@link
 107  * #allocateDirect(int) allocateDirect} factory method of this class.  The
 108  * buffers returned by this method typically have somewhat higher allocation
 109  * and deallocation costs than non-direct buffers.  The contents of direct
 110  * buffers may reside outside of the normal garbage-collected heap, and so
 111  * their impact upon the memory footprint of an application might not be
 112  * obvious.  It is therefore recommended that direct buffers be allocated
 113  * primarily for large, long-lived buffers that are subject to the underlying
 114  * system's native I/O operations.  In general it is best to allocate direct
 115  * buffers only when they yield a measureable gain in program performance.
 116  *
 117  * <p> A direct byte buffer may also be created by {@link
 118  * java.nio.channels.FileChannel#map mapping} a region of a file
 119  * directly into memory.  An implementation of the Java platform may optionally
 120  * support the creation of direct byte buffers from native code via JNI.  If an
 121  * instance of one of these kinds of buffers refers to an inaccessible region
 122  * of memory then an attempt to access that region will not change the buffer's
 123  * content and will cause an unspecified exception to be thrown either at the
 124  * time of the access or at some later time.
 125  *
 126  * <p> Whether a byte buffer is direct or non-direct may be determined by
 127  * invoking its {@link #isDirect isDirect} method.  This method is provided so
 128  * that explicit buffer management can be done in performance-critical code.
 129  *
 130  *
 131  * <a name="bin"></a>
 132  * <h2> Access to binary data </h2>
 133  *
 134  * <p> This class defines methods for reading and writing values of all other
 135  * primitive types, except {@code boolean}.  Primitive values are translated
 136  * to (or from) sequences of bytes according to the buffer's current byte
 137  * order, which may be retrieved and modified via the {@link #order order}
 138  * methods.  Specific byte orders are represented by instances of the {@link
 139  * ByteOrder} class.  The initial order of a byte buffer is always {@link
 140  * ByteOrder#BIG_ENDIAN BIG_ENDIAN}.
 141  *
 142  * <p> For access to heterogeneous binary data, that is, sequences of values of
 143  * different types, this class defines a family of absolute and relative
 144  * <i>get</i> and <i>put</i> methods for each type.  For 32-bit floating-point
 145  * values, for example, this class defines:
 146  *
 147  * <blockquote><pre>
 148  * float  {@link #getFloat()}
 149  * float  {@link #getFloat(int) getFloat(int index)}
 150  *  void  {@link #putFloat(float) putFloat(float f)}
 151  *  void  {@link #putFloat(int,float) putFloat(int index, float f)}</pre></blockquote>
 152  *
 153  * <p> Corresponding methods are defined for the types {@code char,
 154  * short, int, long}, and {@code double}.  The index
 155  * parameters of the absolute <i>get</i> and <i>put</i> methods are in terms of
 156  * bytes rather than of the type being read or written.
 157  *
 158  * <a name="views"></a>
 159  *
 160  * <p> For access to homogeneous binary data, that is, sequences of values of
 161  * the same type, this class defines methods that can create <i>views</i> of a
 162  * given byte buffer.  A <i>view buffer</i> is simply another buffer whose
 163  * content is backed by the byte buffer.  Changes to the byte buffer's content
 164  * will be visible in the view buffer, and vice versa; the two buffers'
 165  * position, limit, and mark values are independent.  The {@link
 166  * #asFloatBuffer() asFloatBuffer} method, for example, creates an instance of
 167  * the {@link FloatBuffer} class that is backed by the byte buffer upon which
 168  * the method is invoked.  Corresponding view-creation methods are defined for
 169  * the types {@code char, short, int, long}, and {@code double}.
 170  *
 171  * <p> View buffers have three important advantages over the families of
 172  * type-specific <i>get</i> and <i>put</i> methods described above:
 173  *
 174  * <ul>
 175  *
 176  *   <li><p> A view buffer is indexed not in terms of bytes but rather in terms
 177  *   of the type-specific size of its values;  </p></li>
 178  *
 179  *   <li><p> A view buffer provides relative bulk <i>get</i> and <i>put</i>
 180  *   methods that can transfer contiguous sequences of values between a buffer
 181  *   and an array or some other buffer of the same type; and  </p></li>
 182  *
 183  *   <li><p> A view buffer is potentially much more efficient because it will
 184  *   be direct if, and only if, its backing byte buffer is direct.  </p></li>
 185  *
 186  * </ul>
 187  *
 188  * <p> The byte order of a view buffer is fixed to be that of its byte buffer
 189  * at the time that the view is created.  </p>
 190  *
 191 #end[byte]
 192 *
 193 #if[!byte]
 194  *
 195  * <p> Like a byte buffer, $a$ $type$ buffer is either <a
 196  * href="ByteBuffer.html#direct"><i>direct</i> or <i>non-direct</i></a>.  A
 197  * $type$ buffer created via the {@code wrap} methods of this class will
 198  * be non-direct.  $A$ $type$ buffer created as a view of a byte buffer will
 199  * be direct if, and only if, the byte buffer itself is direct.  Whether or not
 200  * $a$ $type$ buffer is direct may be determined by invoking the {@link
 201  * #isDirect isDirect} method.  </p>
 202  *
 203 #end[!byte]
 204 *
 205 #if[char]
 206  *
 207  * <p> This class implements the {@link CharSequence} interface so that
 208  * character buffers may be used wherever character sequences are accepted, for
 209  * example in the regular-expression package {@link java.util.regex}.
 210  * </p>
 211  *
 212 #end[char]
 213  *
 214 #if[byte]
 215  * <h2> Invocation chaining </h2>
 216 #end[byte]
 217  *
 218  * <p> Methods in this class that do not otherwise have a value to return are
 219  * specified to return the buffer upon which they are invoked.  This allows
 220  * method invocations to be chained.
 221  *
 222 #if[byte]
 223  *
 224  * The sequence of statements
 225  *
 226  * <blockquote><pre>
 227  * bb.putInt(0xCAFEBABE);
 228  * bb.putShort(3);
 229  * bb.putShort(45);</pre></blockquote>
 230  *
 231  * can, for example, be replaced by the single statement
 232  *
 233  * <blockquote><pre>
 234  * bb.putInt(0xCAFEBABE).putShort(3).putShort(45);</pre></blockquote>
 235  *
 236 #end[byte]
 237 #if[char]
 238  *
 239  * The sequence of statements
 240  *
 241  * <blockquote><pre>
 242  * cb.put("text/");
 243  * cb.put(subtype);
 244  * cb.put("; charset=");
 245  * cb.put(enc);</pre></blockquote>
 246  *
 247  * can, for example, be replaced by the single statement
 248  *
 249  * <blockquote><pre>
 250  * cb.put("text/").put(subtype).put("; charset=").put(enc);</pre></blockquote>
 251  *
 252 #end[char]
 253  *
 254  *
 255  * @author Mark Reinhold
 256  * @author JSR-51 Expert Group
 257  * @since 1.4
 258  */
 259 
 260 public abstract class $Type$Buffer
 261     extends Buffer
 262     implements Comparable<$Type$Buffer>{#if[char]?, Appendable, CharSequence, Readable}
 263 {
 264 
 265     // These fields are declared here rather than in Heap-X-Buffer in order to
 266     // reduce the number of virtual method invocations needed to access these
 267     // values, which is especially costly when coding small buffers.
 268     //
 269     final $type$[] hb;                  // Non-null only for heap buffers
 270     final int offset;
 271     boolean isReadOnly;
 272 
 273     // Creates a new buffer with the given mark, position, limit, capacity,
 274     // backing array, and array offset
 275     //
 276     $Type$Buffer(int mark, int pos, int lim, int cap,   // package-private
 277                  $type$[] hb, int offset)
 278     {
 279         super(mark, pos, lim, cap);
 280         this.hb = hb;
 281         this.offset = offset;
 282     }
 283 
 284     // Creates a new buffer with the given mark, position, limit, and capacity
 285     //
 286     $Type$Buffer(int mark, int pos, int lim, int cap) { // package-private
 287         this(mark, pos, lim, cap, null, 0);
 288     }
 289 
 290 #if[byte]
 291 
 292     /**
 293      * Allocates a new direct $type$ buffer.
 294      *
 295      * <p> The new buffer's position will be zero, its limit will be its
 296      * capacity, its mark will be undefined, each of its elements will be
 297      * initialized to zero, and its byte order will be
 298      * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}.  Whether or not it has a
 299      * {@link #hasArray backing array} is unspecified.
 300      *
 301      * @param  capacity
 302      *         The new buffer's capacity, in $type$s
 303      *
 304      * @return  The new $type$ buffer
 305      *
 306      * @throws  IllegalArgumentException
 307      *          If the {@code capacity} is a negative integer
 308      */
 309     public static $Type$Buffer allocateDirect(int capacity) {
 310         return new Direct$Type$Buffer(capacity);
 311     }
 312 
 313 #end[byte]
 314 
 315     /**
 316      * Allocates a new $type$ buffer.
 317      *
 318      * <p> The new buffer's position will be zero, its limit will be its
 319      * capacity, its mark will be undefined, each of its elements will be
 320      * initialized to zero, and its byte order will be
 321 #if[byte]
 322      * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}.
 323 #else[byte]
 324      * the {@link ByteOrder#nativeOrder native order} of the underlying
 325      * hardware.
 326 #end[byte]
 327      * It will have a {@link #array backing array}, and its
 328      * {@link #arrayOffset array offset} will be zero.
 329      *
 330      * @param  capacity
 331      *         The new buffer's capacity, in $type$s
 332      *
 333      * @return  The new $type$ buffer
 334      *
 335      * @throws  IllegalArgumentException
 336      *          If the {@code capacity} is a negative integer
 337      */
 338     public static $Type$Buffer allocate(int capacity) {
 339         if (capacity < 0)
 340             throw createCapacityException(capacity);
 341         return new Heap$Type$Buffer(capacity, capacity);
 342     }
 343 
 344     /**
 345      * Wraps $a$ $type$ array into a buffer.
 346      *
 347      * <p> The new buffer will be backed by the given $type$ array;
 348      * that is, modifications to the buffer will cause the array to be modified
 349      * and vice versa.  The new buffer's capacity will be
 350      * {@code array.length}, its position will be {@code offset}, its limit
 351      * will be {@code offset + length}, its mark will be undefined, and its
 352      * byte order will be
 353 #if[byte]
 354      * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}.
 355 #else[byte]
 356      * the {@link ByteOrder#nativeOrder native order} of the underlying
 357      * hardware.
 358 #end[byte]
 359      * Its {@link #array backing array} will be the given array, and
 360      * its {@link #arrayOffset array offset} will be zero.  </p>
 361      *
 362      * @param  array
 363      *         The array that will back the new buffer
 364      *
 365      * @param  offset
 366      *         The offset of the subarray to be used; must be non-negative and
 367      *         no larger than {@code array.length}.  The new buffer's position
 368      *         will be set to this value.
 369      *
 370      * @param  length
 371      *         The length of the subarray to be used;
 372      *         must be non-negative and no larger than
 373      *         {@code array.length - offset}.
 374      *         The new buffer's limit will be set to {@code offset + length}.
 375      *
 376      * @return  The new $type$ buffer
 377      *
 378      * @throws  IndexOutOfBoundsException
 379      *          If the preconditions on the {@code offset} and {@code length}
 380      *          parameters do not hold
 381      */
 382     public static $Type$Buffer wrap($type$[] array,
 383                                     int offset, int length)
 384     {
 385         try {
 386             return new Heap$Type$Buffer(array, offset, length);
 387         } catch (IllegalArgumentException x) {
 388             throw new IndexOutOfBoundsException();
 389         }
 390     }
 391 
 392     /**
 393      * Wraps $a$ $type$ array into a buffer.
 394      *
 395      * <p> The new buffer will be backed by the given $type$ array;
 396      * that is, modifications to the buffer will cause the array to be modified
 397      * and vice versa.  The new buffer's capacity and limit will be
 398      * {@code array.length}, its position will be zero, its mark will be
 399      * undefined, and its byte order will be
 400 #if[byte]
 401      * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}.
 402 #else[byte]
 403      * the {@link ByteOrder#nativeOrder native order} of the underlying
 404      * hardware.
 405 #end[byte]
 406      * Its {@link #array backing array} will be the given array, and its
 407      * {@link #arrayOffset array offset} will be zero.  </p>
 408      *
 409      * @param  array
 410      *         The array that will back this buffer
 411      *
 412      * @return  The new $type$ buffer
 413      */
 414     public static $Type$Buffer wrap($type$[] array) {
 415         return wrap(array, 0, array.length);
 416     }
 417 
 418 #if[char]
 419 
 420     /**
 421      * Attempts to read characters into the specified character buffer.
 422      * The buffer is used as a repository of characters as-is: the only
 423      * changes made are the results of a put operation. No flipping or
 424      * rewinding of the buffer is performed.
 425      *
 426      * @param target the buffer to read characters into
 427      * @return The number of characters added to the buffer, or
 428      *         -1 if this source of characters is at its end
 429      * @throws IOException if an I/O error occurs
 430      * @throws NullPointerException if target is null
 431      * @throws ReadOnlyBufferException if target is a read only buffer
 432      * @since 1.5
 433      */
 434     public int read(CharBuffer target) throws IOException {
 435         // Determine the number of bytes n that can be transferred
 436         int targetRemaining = target.remaining();
 437         int remaining = remaining();
 438         if (remaining == 0)
 439             return -1;
 440         int n = Math.min(remaining, targetRemaining);
 441         int limit = limit();
 442         // Set source limit to prevent target overflow
 443         if (targetRemaining < remaining)
 444             limit(position() + n);
 445         try {
 446             if (n > 0)
 447                 target.put(this);
 448         } finally {
 449             limit(limit); // restore real limit
 450         }
 451         return n;
 452     }
 453 
 454     /**
 455      * Wraps a character sequence into a buffer.
 456      *
 457      * <p> The content of the new, read-only buffer will be the content of the
 458      * given character sequence.  The buffer's capacity will be
 459      * {@code csq.length()}, its position will be {@code start}, its limit
 460      * will be {@code end}, and its mark will be undefined.  </p>
 461      *
 462      * @param  csq
 463      *         The character sequence from which the new character buffer is to
 464      *         be created
 465      *
 466      * @param  start
 467      *         The index of the first character to be used;
 468      *         must be non-negative and no larger than {@code csq.length()}.
 469      *         The new buffer's position will be set to this value.
 470      *
 471      * @param  end
 472      *         The index of the character following the last character to be
 473      *         used; must be no smaller than {@code start} and no larger
 474      *         than {@code csq.length()}.
 475      *         The new buffer's limit will be set to this value.
 476      *
 477      * @return  The new character buffer
 478      *
 479      * @throws  IndexOutOfBoundsException
 480      *          If the preconditions on the {@code start} and {@code end}
 481      *          parameters do not hold
 482      */
 483     public static CharBuffer wrap(CharSequence csq, int start, int end) {
 484         try {
 485             return new StringCharBuffer(csq, start, end);
 486         } catch (IllegalArgumentException x) {
 487             throw new IndexOutOfBoundsException();
 488         }
 489     }
 490 
 491     /**
 492      * Wraps a character sequence into a buffer.
 493      *
 494      * <p> The content of the new, read-only buffer will be the content of the
 495      * given character sequence.  The new buffer's capacity and limit will be
 496      * {@code csq.length()}, its position will be zero, and its mark will be
 497      * undefined.  </p>
 498      *
 499      * @param  csq
 500      *         The character sequence from which the new character buffer is to
 501      *         be created
 502      *
 503      * @return  The new character buffer
 504      */
 505     public static CharBuffer wrap(CharSequence csq) {
 506         return wrap(csq, 0, csq.length());
 507     }
 508 
 509 #end[char]
 510 
 511     /**
 512      * Creates a new $type$ buffer whose content is a shared subsequence of
 513      * this buffer's content.
 514      *
 515      * <p> The content of the new buffer will start at this buffer's current
 516      * position.  Changes to this buffer's content will be visible in the new
 517      * buffer, and vice versa; the two buffers' position, limit, and mark
 518      * values will be independent.
 519      *
 520      * <p> The new buffer's position will be zero, its capacity and its limit
 521      * will be the number of $type$s remaining in this buffer, its mark will be
 522      * undefined, and its byte order will be
 523 #if[byte]
 524      * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}.
 525 #else[byte]
 526      * identical to that of this buffer.
 527 #end[byte]
 528      * The new buffer will be direct if, and only if, this buffer is direct, and
 529      * it will be read-only if, and only if, this buffer is read-only.  </p>
 530      *
 531      * @return  The new $type$ buffer
 532 #if[byte]
 533      *
 534      * @see #alignedSlice(int)
 535 #end[byte]
 536      */
 537     @Override
 538     public abstract $Type$Buffer slice();
 539 
 540     /**
 541      * Creates a new $type$ buffer that shares this buffer's content.
 542      *
 543      * <p> The content of the new buffer will be that of this buffer.  Changes
 544      * to this buffer's content will be visible in the new buffer, and vice
 545      * versa; the two buffers' position, limit, and mark values will be
 546      * independent.
 547      *
 548      * <p> The new buffer's capacity, limit, position,
 549 #if[byte]
 550      * and mark values will be identical to those of this buffer, and its byte
 551      * order will be {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}.
 552 #else[byte]
 553      * mark values, and byte order will be identical to those of this buffer.
 554 #end[byte]
 555      * The new buffer will be direct if, and only if, this buffer is direct, and
 556      * it will be read-only if, and only if, this buffer is read-only.  </p>
 557      *
 558      * @return  The new $type$ buffer
 559      */
 560     @Override
 561     public abstract $Type$Buffer duplicate();
 562 
 563     /**
 564      * Creates a new, read-only $type$ buffer that shares this buffer's
 565      * content.
 566      *
 567      * <p> The content of the new buffer will be that of this buffer.  Changes
 568      * to this buffer's content will be visible in the new buffer; the new
 569      * buffer itself, however, will be read-only and will not allow the shared
 570      * content to be modified.  The two buffers' position, limit, and mark
 571      * values will be independent.
 572      *
 573      * <p> The new buffer's capacity, limit, position,
 574 #if[byte]
 575      * and mark values will be identical to those of this buffer, and its byte
 576      * order will be {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}.
 577 #else[byte]
 578      * mark values, and byte order will be identical to those of this buffer.
 579 #end[byte]
 580      *
 581      * <p> If this buffer is itself read-only then this method behaves in
 582      * exactly the same way as the {@link #duplicate duplicate} method.  </p>
 583      *
 584      * @return  The new, read-only $type$ buffer
 585      */
 586     public abstract $Type$Buffer asReadOnlyBuffer();
 587 
 588 
 589     // -- Singleton get/put methods --
 590 
 591     /**
 592      * Relative <i>get</i> method.  Reads the $type$ at this buffer's
 593      * current position, and then increments the position.
 594      *
 595      * @return  The $type$ at the buffer's current position
 596      *
 597      * @throws  BufferUnderflowException
 598      *          If the buffer's current position is not smaller than its limit
 599      */
 600     public abstract $type$ get();
 601 
 602     /**
 603      * Relative <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
 604      *
 605      * <p> Writes the given $type$ into this buffer at the current
 606      * position, and then increments the position. </p>
 607      *
 608      * @param  $x$
 609      *         The $type$ to be written
 610      *
 611      * @return  This buffer
 612      *
 613      * @throws  BufferOverflowException
 614      *          If this buffer's current position is not smaller than its limit
 615      *
 616      * @throws  ReadOnlyBufferException
 617      *          If this buffer is read-only
 618      */
 619     public abstract $Type$Buffer put($type$ $x$);
 620 
 621     /**
 622      * Absolute <i>get</i> method.  Reads the $type$ at the given
 623      * index.
 624      *
 625      * @param  index
 626      *         The index from which the $type$ will be read
 627      *
 628      * @return  The $type$ at the given index
 629      *
 630      * @throws  IndexOutOfBoundsException
 631      *          If {@code index} is negative
 632      *          or not smaller than the buffer's limit
 633      */
 634     public abstract $type$ get(int index);
 635 
 636 #if[streamableType]
 637     /**
 638      * Absolute <i>get</i> method.  Reads the $type$ at the given
 639      * index without any validation of the index.
 640      *
 641      * @param  index
 642      *         The index from which the $type$ will be read
 643      *
 644      * @return  The $type$ at the given index
 645      */
 646     abstract $type$ getUnchecked(int index);   // package-private
 647 #end[streamableType]
 648 
 649     /**
 650      * Absolute <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
 651      *
 652      * <p> Writes the given $type$ into this buffer at the given
 653      * index. </p>
 654      *
 655      * @param  index
 656      *         The index at which the $type$ will be written
 657      *
 658      * @param  $x$
 659      *         The $type$ value to be written
 660      *
 661      * @return  This buffer
 662      *
 663      * @throws  IndexOutOfBoundsException
 664      *          If {@code index} is negative
 665      *          or not smaller than the buffer's limit
 666      *
 667      * @throws  ReadOnlyBufferException
 668      *          If this buffer is read-only
 669      */
 670     public abstract $Type$Buffer put(int index, $type$ $x$);
 671 
 672 
 673     // -- Bulk get operations --
 674 
 675     /**
 676      * Relative bulk <i>get</i> method.
 677      *
 678      * <p> This method transfers $type$s from this buffer into the given
 679      * destination array.  If there are fewer $type$s remaining in the
 680      * buffer than are required to satisfy the request, that is, if
 681      * {@code length}&nbsp;{@code >}&nbsp;{@code remaining()}, then no
 682      * $type$s are transferred and a {@link BufferUnderflowException} is
 683      * thrown.
 684      *
 685      * <p> Otherwise, this method copies {@code length} $type$s from this
 686      * buffer into the given array, starting at the current position of this
 687      * buffer and at the given offset in the array.  The position of this
 688      * buffer is then incremented by {@code length}.
 689      *
 690      * <p> In other words, an invocation of this method of the form
 691      * <code>src.get(dst,&nbsp;off,&nbsp;len)</code> has exactly the same effect as
 692      * the loop
 693      *
 694      * <pre>{@code
 695      *     for (int i = off; i < off + len; i++)
 696      *         dst[i] = src.get():
 697      * }</pre>
 698      *
 699      * except that it first checks that there are sufficient $type$s in
 700      * this buffer and it is potentially much more efficient.
 701      *
 702      * @param  dst
 703      *         The array into which $type$s are to be written
 704      *
 705      * @param  offset
 706      *         The offset within the array of the first $type$ to be
 707      *         written; must be non-negative and no larger than
 708      *         {@code dst.length}
 709      *
 710      * @param  length
 711      *         The maximum number of $type$s to be written to the given
 712      *         array; must be non-negative and no larger than
 713      *         {@code dst.length - offset}
 714      *
 715      * @return  This buffer
 716      *
 717      * @throws  BufferUnderflowException
 718      *          If there are fewer than {@code length} $type$s
 719      *          remaining in this buffer
 720      *
 721      * @throws  IndexOutOfBoundsException
 722      *          If the preconditions on the {@code offset} and {@code length}
 723      *          parameters do not hold
 724      */
 725     public $Type$Buffer get($type$[] dst, int offset, int length) {
 726         checkBounds(offset, length, dst.length);
 727         if (length > remaining())
 728             throw new BufferUnderflowException();
 729         int end = offset + length;
 730         for (int i = offset; i < end; i++)
 731             dst[i] = get();
 732         return this;
 733     }
 734 
 735     /**
 736      * Relative bulk <i>get</i> method.
 737      *
 738      * <p> This method transfers $type$s from this buffer into the given
 739      * destination array.  An invocation of this method of the form
 740      * {@code src.get(a)} behaves in exactly the same way as the invocation
 741      *
 742      * <pre>
 743      *     src.get(a, 0, a.length) </pre>
 744      *
 745      * @param   dst
 746      *          The destination array
 747      *
 748      * @return  This buffer
 749      *
 750      * @throws  BufferUnderflowException
 751      *          If there are fewer than {@code length} $type$s
 752      *          remaining in this buffer
 753      */
 754     public $Type$Buffer get($type$[] dst) {
 755         return get(dst, 0, dst.length);
 756     }
 757 
 758 
 759     // -- Bulk put operations --
 760 
 761     /**
 762      * Relative bulk <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
 763      *
 764      * <p> This method transfers the $type$s remaining in the given source
 765      * buffer into this buffer.  If there are more $type$s remaining in the
 766      * source buffer than in this buffer, that is, if
 767      * {@code src.remaining()}&nbsp;{@code >}&nbsp;{@code remaining()},
 768      * then no $type$s are transferred and a {@link
 769      * BufferOverflowException} is thrown.
 770      *
 771      * <p> Otherwise, this method copies
 772      * <i>n</i>&nbsp;=&nbsp;{@code src.remaining()} $type$s from the given
 773      * buffer into this buffer, starting at each buffer's current position.
 774      * The positions of both buffers are then incremented by <i>n</i>.
 775      *
 776      * <p> In other words, an invocation of this method of the form
 777      * {@code dst.put(src)} has exactly the same effect as the loop
 778      *
 779      * <pre>
 780      *     while (src.hasRemaining())
 781      *         dst.put(src.get()); </pre>
 782      *
 783      * except that it first checks that there is sufficient space in this
 784      * buffer and it is potentially much more efficient.
 785      *
 786      * @param  src
 787      *         The source buffer from which $type$s are to be read;
 788      *         must not be this buffer
 789      *
 790      * @return  This buffer
 791      *
 792      * @throws  BufferOverflowException
 793      *          If there is insufficient space in this buffer
 794      *          for the remaining $type$s in the source buffer
 795      *
 796      * @throws  IllegalArgumentException
 797      *          If the source buffer is this buffer
 798      *
 799      * @throws  ReadOnlyBufferException
 800      *          If this buffer is read-only
 801      */
 802     public $Type$Buffer put($Type$Buffer src) {
 803         if (src == this)
 804             throw createSameBufferException();
 805         if (isReadOnly())
 806             throw new ReadOnlyBufferException();
 807         int n = src.remaining();
 808         if (n > remaining())
 809             throw new BufferOverflowException();
 810         for (int i = 0; i < n; i++)
 811             put(src.get());
 812         return this;
 813     }
 814 
 815     /**
 816      * Relative bulk <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
 817      *
 818      * <p> This method transfers $type$s into this buffer from the given
 819      * source array.  If there are more $type$s to be copied from the array
 820      * than remain in this buffer, that is, if
 821      * {@code length}&nbsp;{@code >}&nbsp;{@code remaining()}, then no
 822      * $type$s are transferred and a {@link BufferOverflowException} is
 823      * thrown.
 824      *
 825      * <p> Otherwise, this method copies {@code length} $type$s from the
 826      * given array into this buffer, starting at the given offset in the array
 827      * and at the current position of this buffer.  The position of this buffer
 828      * is then incremented by {@code length}.
 829      *
 830      * <p> In other words, an invocation of this method of the form
 831      * <code>dst.put(src,&nbsp;off,&nbsp;len)</code> has exactly the same effect as
 832      * the loop
 833      *
 834      * <pre>{@code
 835      *     for (int i = off; i < off + len; i++)
 836      *         dst.put(a[i]);
 837      * }</pre>
 838      *
 839      * except that it first checks that there is sufficient space in this
 840      * buffer and it is potentially much more efficient.
 841      *
 842      * @param  src
 843      *         The array from which $type$s are to be read
 844      *
 845      * @param  offset
 846      *         The offset within the array of the first $type$ to be read;
 847      *         must be non-negative and no larger than {@code array.length}
 848      *
 849      * @param  length
 850      *         The number of $type$s to be read from the given array;
 851      *         must be non-negative and no larger than
 852      *         {@code array.length - offset}
 853      *
 854      * @return  This buffer
 855      *
 856      * @throws  BufferOverflowException
 857      *          If there is insufficient space in this buffer
 858      *
 859      * @throws  IndexOutOfBoundsException
 860      *          If the preconditions on the {@code offset} and {@code length}
 861      *          parameters do not hold
 862      *
 863      * @throws  ReadOnlyBufferException
 864      *          If this buffer is read-only
 865      */
 866     public $Type$Buffer put($type$[] src, int offset, int length) {
 867         checkBounds(offset, length, src.length);
 868         if (length > remaining())
 869             throw new BufferOverflowException();
 870         int end = offset + length;
 871         for (int i = offset; i < end; i++)
 872             this.put(src[i]);
 873         return this;
 874     }
 875 
 876     /**
 877      * Relative bulk <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
 878      *
 879      * <p> This method transfers the entire content of the given source
 880      * $type$ array into this buffer.  An invocation of this method of the
 881      * form {@code dst.put(a)} behaves in exactly the same way as the
 882      * invocation
 883      *
 884      * <pre>
 885      *     dst.put(a, 0, a.length) </pre>
 886      *
 887      * @param   src
 888      *          The source array
 889      *
 890      * @return  This buffer
 891      *
 892      * @throws  BufferOverflowException
 893      *          If there is insufficient space in this buffer
 894      *
 895      * @throws  ReadOnlyBufferException
 896      *          If this buffer is read-only
 897      */
 898     public final $Type$Buffer put($type$[] src) {
 899         return put(src, 0, src.length);
 900     }
 901 
 902 #if[char]
 903 
 904     /**
 905      * Relative bulk <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
 906      *
 907      * <p> This method transfers $type$s from the given string into this
 908      * buffer.  If there are more $type$s to be copied from the string than
 909      * remain in this buffer, that is, if
 910      * <code>end&nbsp;-&nbsp;start</code>&nbsp;{@code >}&nbsp;{@code remaining()},
 911      * then no $type$s are transferred and a {@link
 912      * BufferOverflowException} is thrown.
 913      *
 914      * <p> Otherwise, this method copies
 915      * <i>n</i>&nbsp;=&nbsp;{@code end}&nbsp;-&nbsp;{@code start} $type$s
 916      * from the given string into this buffer, starting at the given
 917      * {@code start} index and at the current position of this buffer.  The
 918      * position of this buffer is then incremented by <i>n</i>.
 919      *
 920      * <p> In other words, an invocation of this method of the form
 921      * <code>dst.put(src,&nbsp;start,&nbsp;end)</code> has exactly the same effect
 922      * as the loop
 923      *
 924      * <pre>{@code
 925      *     for (int i = start; i < end; i++)
 926      *         dst.put(src.charAt(i));
 927      * }</pre>
 928      *
 929      * except that it first checks that there is sufficient space in this
 930      * buffer and it is potentially much more efficient.
 931      *
 932      * @param  src
 933      *         The string from which $type$s are to be read
 934      *
 935      * @param  start
 936      *         The offset within the string of the first $type$ to be read;
 937      *         must be non-negative and no larger than
 938      *         {@code string.length()}
 939      *
 940      * @param  end
 941      *         The offset within the string of the last $type$ to be read,
 942      *         plus one; must be non-negative and no larger than
 943      *         {@code string.length()}
 944      *
 945      * @return  This buffer
 946      *
 947      * @throws  BufferOverflowException
 948      *          If there is insufficient space in this buffer
 949      *
 950      * @throws  IndexOutOfBoundsException
 951      *          If the preconditions on the {@code start} and {@code end}
 952      *          parameters do not hold
 953      *
 954      * @throws  ReadOnlyBufferException
 955      *          If this buffer is read-only
 956      */
 957     public $Type$Buffer put(String src, int start, int end) {
 958         checkBounds(start, end - start, src.length());
 959         if (isReadOnly())
 960             throw new ReadOnlyBufferException();
 961         if (end - start > remaining())
 962             throw new BufferOverflowException();
 963         for (int i = start; i < end; i++)
 964             this.put(src.charAt(i));
 965         return this;
 966     }
 967 
 968     /**
 969      * Relative bulk <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
 970      *
 971      * <p> This method transfers the entire content of the given source string
 972      * into this buffer.  An invocation of this method of the form
 973      * {@code dst.put(s)} behaves in exactly the same way as the invocation
 974      *
 975      * <pre>
 976      *     dst.put(s, 0, s.length()) </pre>
 977      *
 978      * @param   src
 979      *          The source string
 980      *
 981      * @return  This buffer
 982      *
 983      * @throws  BufferOverflowException
 984      *          If there is insufficient space in this buffer
 985      *
 986      * @throws  ReadOnlyBufferException
 987      *          If this buffer is read-only
 988      */
 989     public final $Type$Buffer put(String src) {
 990         return put(src, 0, src.length());
 991     }
 992 
 993 #end[char]
 994 
 995 
 996     // -- Other stuff --
 997 
 998     /**
 999      * Tells whether or not this buffer is backed by an accessible $type$
1000      * array.
1001      *
1002      * <p> If this method returns {@code true} then the {@link #array() array}
1003      * and {@link #arrayOffset() arrayOffset} methods may safely be invoked.
1004      * </p>
1005      *
1006      * @return  {@code true} if, and only if, this buffer
1007      *          is backed by an array and is not read-only
1008      */
1009     public final boolean hasArray() {
1010         return (hb != null) && !isReadOnly;
1011     }
1012 
1013     /**
1014      * Returns the $type$ array that backs this
1015      * buffer&nbsp;&nbsp;<i>(optional operation)</i>.
1016      *
1017      * <p> Modifications to this buffer's content will cause the returned
1018      * array's content to be modified, and vice versa.
1019      *
1020      * <p> Invoke the {@link #hasArray hasArray} method before invoking this
1021      * method in order to ensure that this buffer has an accessible backing
1022      * array.  </p>
1023      *
1024      * @return  The array that backs this buffer
1025      *
1026      * @throws  ReadOnlyBufferException
1027      *          If this buffer is backed by an array but is read-only
1028      *
1029      * @throws  UnsupportedOperationException
1030      *          If this buffer is not backed by an accessible array
1031      */
1032     public final $type$[] array() {
1033         if (hb == null)
1034             throw new UnsupportedOperationException();
1035         if (isReadOnly)
1036             throw new ReadOnlyBufferException();
1037         return hb;
1038     }
1039 
1040     /**
1041      * Returns the offset within this buffer's backing array of the first
1042      * element of the buffer&nbsp;&nbsp;<i>(optional operation)</i>.
1043      *
1044      * <p> If this buffer is backed by an array then buffer position <i>p</i>
1045      * corresponds to array index <i>p</i>&nbsp;+&nbsp;{@code arrayOffset()}.
1046      *
1047      * <p> Invoke the {@link #hasArray hasArray} method before invoking this
1048      * method in order to ensure that this buffer has an accessible backing
1049      * array.  </p>
1050      *
1051      * @return  The offset within this buffer's array
1052      *          of the first element of the buffer
1053      *
1054      * @throws  ReadOnlyBufferException
1055      *          If this buffer is backed by an array but is read-only
1056      *
1057      * @throws  UnsupportedOperationException
1058      *          If this buffer is not backed by an accessible array
1059      */
1060     public final int arrayOffset() {
1061         if (hb == null)
1062             throw new UnsupportedOperationException();
1063         if (isReadOnly)
1064             throw new ReadOnlyBufferException();
1065         return offset;
1066     }
1067 
1068     // -- Covariant return type overrides
1069 
1070     /**
1071      * {@inheritDoc}
1072      * @since 9
1073      */
1074     @Override
1075     public
1076 #if[!byte]
1077     final
1078 #end[!byte]
1079     $Type$Buffer position(int newPosition) {
1080         super.position(newPosition);
1081         return this;
1082     }
1083     
1084     /**
1085      * {@inheritDoc}
1086      * @since 9
1087      */
1088     @Override
1089     public
1090 #if[!byte]
1091     final
1092 #end[!byte]
1093     $Type$Buffer limit(int newLimit) {
1094         super.limit(newLimit);
1095         return this;
1096     }
1097     
1098     /**
1099      * {@inheritDoc}
1100      * @since 9
1101      */
1102     @Override
1103     public 
1104 #if[!byte]
1105     final
1106 #end[!byte]
1107     $Type$Buffer mark() {
1108         super.mark();
1109         return this;
1110     }
1111 
1112     /**
1113      * {@inheritDoc}
1114      * @since 9
1115      */
1116     @Override
1117     public 
1118 #if[!byte]
1119     final
1120 #end[!byte]
1121     $Type$Buffer reset() {
1122         super.reset();
1123         return this;
1124     }
1125 
1126     /**
1127      * {@inheritDoc}
1128      * @since 9
1129      */
1130     @Override
1131     public 
1132 #if[!byte]
1133     final
1134 #end[!byte]
1135     $Type$Buffer clear() {
1136         super.clear();
1137         return this;
1138     }
1139 
1140     /**
1141      * {@inheritDoc}
1142      * @since 9
1143      */
1144     @Override
1145     public 
1146 #if[!byte]
1147     final
1148 #end[!byte]
1149     $Type$Buffer flip() {
1150         super.flip();
1151         return this;
1152     }
1153 
1154     /**
1155      * {@inheritDoc}
1156      * @since 9
1157      */
1158     @Override
1159     public 
1160 #if[!byte]
1161     final
1162 #end[!byte]
1163     $Type$Buffer rewind() {
1164         super.rewind();
1165         return this;
1166     }
1167 
1168     /**
1169      * Compacts this buffer&nbsp;&nbsp;<i>(optional operation)</i>.
1170      *
1171      * <p> The $type$s between the buffer's current position and its limit,
1172      * if any, are copied to the beginning of the buffer.  That is, the
1173      * $type$ at index <i>p</i>&nbsp;=&nbsp;{@code position()} is copied
1174      * to index zero, the $type$ at index <i>p</i>&nbsp;+&nbsp;1 is copied
1175      * to index one, and so forth until the $type$ at index
1176      * {@code limit()}&nbsp;-&nbsp;1 is copied to index
1177      * <i>n</i>&nbsp;=&nbsp;{@code limit()}&nbsp;-&nbsp;{@code 1}&nbsp;-&nbsp;<i>p</i>.
1178      * The buffer's position is then set to <i>n+1</i> and its limit is set to
1179      * its capacity.  The mark, if defined, is discarded.
1180      *
1181      * <p> The buffer's position is set to the number of $type$s copied,
1182      * rather than to zero, so that an invocation of this method can be
1183      * followed immediately by an invocation of another relative <i>put</i>
1184      * method. </p>
1185      *
1186 #if[byte]
1187      *
1188      * <p> Invoke this method after writing data from a buffer in case the
1189      * write was incomplete.  The following loop, for example, copies bytes
1190      * from one channel to another via the buffer {@code buf}:
1191      *
1192      * <blockquote><pre>{@code
1193      *   buf.clear();          // Prepare buffer for use
1194      *   while (in.read(buf) >= 0 || buf.position != 0) {
1195      *       buf.flip();
1196      *       out.write(buf);
1197      *       buf.compact();    // In case of partial write
1198      *   }
1199      * }</pre></blockquote>
1200      *
1201 #end[byte]
1202      *
1203      * @return  This buffer
1204      *
1205      * @throws  ReadOnlyBufferException
1206      *          If this buffer is read-only
1207      */
1208     public abstract $Type$Buffer compact();
1209 
1210     /**
1211      * Tells whether or not this $type$ buffer is direct.
1212      *
1213      * @return  {@code true} if, and only if, this buffer is direct
1214      */
1215     public abstract boolean isDirect();
1216 
1217 #if[!char]
1218 
1219     /**
1220      * Returns a string summarizing the state of this buffer.
1221      *
1222      * @return  A summary string
1223      */
1224     public String toString() {
1225         StringBuffer sb = new StringBuffer();
1226         sb.append(getClass().getName());
1227         sb.append("[pos=");
1228         sb.append(position());
1229         sb.append(" lim=");
1230         sb.append(limit());
1231         sb.append(" cap=");
1232         sb.append(capacity());
1233         sb.append("]");
1234         return sb.toString();
1235     }
1236 
1237 #end[!char]
1238 
1239 
1240     // ## Should really use unchecked accessors here for speed
1241 
1242     /**
1243      * Returns the current hash code of this buffer.
1244      *
1245      * <p> The hash code of a $type$ buffer depends only upon its remaining
1246      * elements; that is, upon the elements from {@code position()} up to, and
1247      * including, the element at {@code limit()}&nbsp;-&nbsp;{@code 1}.
1248      *
1249      * <p> Because buffer hash codes are content-dependent, it is inadvisable
1250      * to use buffers as keys in hash maps or similar data structures unless it
1251      * is known that their contents will not change.  </p>
1252      *
1253      * @return  The current hash code of this buffer
1254      */
1255     public int hashCode() {
1256         int h = 1;
1257         int p = position();
1258         for (int i = limit() - 1; i >= p; i--)
1259 #if[int]
1260             h = 31 * h + get(i);
1261 #else[int]
1262             h = 31 * h + (int)get(i);
1263 #end[int]
1264         return h;
1265     }
1266 
1267     /**
1268      * Tells whether or not this buffer is equal to another object.
1269      *
1270      * <p> Two $type$ buffers are equal if, and only if,
1271      *
1272      * <ol>
1273      *
1274      *   <li><p> They have the same element type,  </p></li>
1275      *
1276      *   <li><p> They have the same number of remaining elements, and
1277      *   </p></li>
1278      *
1279      *   <li><p> The two sequences of remaining elements, considered
1280      *   independently of their starting positions, are pointwise equal.
1281 #if[floatingPointType]
1282      *   This method considers two $type$ elements {@code a} and {@code b}
1283      *   to be equal if
1284      *   {@code (a == b) || ($Fulltype$.isNaN(a) && $Fulltype$.isNaN(b))}.
1285      *   The values {@code -0.0} and {@code +0.0} are considered to be
1286      *   equal, unlike {@link $Fulltype$#equals(Object)}.
1287 #end[floatingPointType]
1288      *   </p></li>
1289      *
1290      * </ol>
1291      *
1292      * <p> A $type$ buffer is not equal to any other type of object.  </p>
1293      *
1294      * @param  ob  The object to which this buffer is to be compared
1295      *
1296      * @return  {@code true} if, and only if, this buffer is equal to the
1297      *           given object
1298      */
1299     public boolean equals(Object ob) {
1300         if (this == ob)
1301             return true;
1302         if (!(ob instanceof $Type$Buffer))
1303             return false;
1304         $Type$Buffer that = ($Type$Buffer)ob;
1305         if (this.remaining() != that.remaining())
1306             return false;
1307         int p = this.position();
1308         for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--)
1309             if (!equals(this.get(i), that.get(j)))
1310                 return false;
1311         return true;
1312     }
1313 
1314     private static boolean equals($type$ x, $type$ y) {
1315 #if[floatingPointType]
1316         return (x == y) || ($Fulltype$.isNaN(x) && $Fulltype$.isNaN(y));
1317 #else[floatingPointType]
1318         return x == y;
1319 #end[floatingPointType]
1320     }
1321 
1322     /**
1323      * Compares this buffer to another.
1324      *
1325      * <p> Two $type$ buffers are compared by comparing their sequences of
1326      * remaining elements lexicographically, without regard to the starting
1327      * position of each sequence within its corresponding buffer.
1328 #if[floatingPointType]
1329      * Pairs of {@code $type$} elements are compared as if by invoking
1330      * {@link $Fulltype$#compare($type$,$type$)}, except that
1331      * {@code -0.0} and {@code 0.0} are considered to be equal.
1332      * {@code $Fulltype$.NaN} is considered by this method to be equal
1333      * to itself and greater than all other {@code $type$} values
1334      * (including {@code $Fulltype$.POSITIVE_INFINITY}).
1335 #else[floatingPointType]
1336      * Pairs of {@code $type$} elements are compared as if by invoking
1337      * {@link $Fulltype$#compare($type$,$type$)}.
1338 #end[floatingPointType]
1339      *
1340      * <p> A $type$ buffer is not comparable to any other type of object.
1341      *
1342      * @return  A negative integer, zero, or a positive integer as this buffer
1343      *          is less than, equal to, or greater than the given buffer
1344      */
1345     public int compareTo($Type$Buffer that) {
1346         int n = this.position() + Math.min(this.remaining(), that.remaining());
1347         for (int i = this.position(), j = that.position(); i < n; i++, j++) {
1348             int cmp = compare(this.get(i), that.get(j));
1349             if (cmp != 0)
1350                 return cmp;
1351         }
1352         return this.remaining() - that.remaining();
1353     }
1354 
1355     private static int compare($type$ x, $type$ y) {
1356 #if[floatingPointType]
1357         return ((x < y)  ? -1 :
1358                 (x > y)  ? +1 :
1359                 (x == y) ?  0 :
1360                 $Fulltype$.isNaN(x) ? ($Fulltype$.isNaN(y) ? 0 : +1) : -1);
1361 #else[floatingPointType]
1362         return $Fulltype$.compare(x, y);
1363 #end[floatingPointType]
1364     }
1365 
1366     // -- Other char stuff --
1367 
1368 #if[char]
1369 
1370     /**
1371      * Returns a string containing the characters in this buffer.
1372      *
1373      * <p> The first character of the resulting string will be the character at
1374      * this buffer's position, while the last character will be the character
1375      * at index {@code limit()}&nbsp;-&nbsp;1.  Invoking this method does not
1376      * change the buffer's position. </p>
1377      *
1378      * @return  The specified string
1379      */
1380     public String toString() {
1381         return toString(position(), limit());
1382     }
1383 
1384     abstract String toString(int start, int end);       // package-private
1385 
1386 
1387     // --- Methods to support CharSequence ---
1388 
1389     /**
1390      * Returns the length of this character buffer.
1391      *
1392      * <p> When viewed as a character sequence, the length of a character
1393      * buffer is simply the number of characters between the position
1394      * (inclusive) and the limit (exclusive); that is, it is equivalent to
1395      * {@code remaining()}. </p>
1396      *
1397      * @return  The length of this character buffer
1398      */
1399     public final int length() {
1400         return remaining();
1401     }
1402 
1403     /**
1404      * Reads the character at the given index relative to the current
1405      * position.
1406      *
1407      * @param  index
1408      *         The index of the character to be read, relative to the position;
1409      *         must be non-negative and smaller than {@code remaining()}
1410      *
1411      * @return  The character at index
1412      *          <code>position()&nbsp;+&nbsp;index</code>
1413      *
1414      * @throws  IndexOutOfBoundsException
1415      *          If the preconditions on {@code index} do not hold
1416      */
1417     public final char charAt(int index) {
1418         return get(position() + checkIndex(index, 1));
1419     }
1420 
1421     /**
1422      * Creates a new character buffer that represents the specified subsequence
1423      * of this buffer, relative to the current position.
1424      *
1425      * <p> The new buffer will share this buffer's content; that is, if the
1426      * content of this buffer is mutable then modifications to one buffer will
1427      * cause the other to be modified.  The new buffer's capacity will be that
1428      * of this buffer, its position will be
1429      * {@code position()}&nbsp;+&nbsp;{@code start}, and its limit will be
1430      * {@code position()}&nbsp;+&nbsp;{@code end}.  The new buffer will be
1431      * direct if, and only if, this buffer is direct, and it will be read-only
1432      * if, and only if, this buffer is read-only.  </p>
1433      *
1434      * @param  start
1435      *         The index, relative to the current position, of the first
1436      *         character in the subsequence; must be non-negative and no larger
1437      *         than {@code remaining()}
1438      *
1439      * @param  end
1440      *         The index, relative to the current position, of the character
1441      *         following the last character in the subsequence; must be no
1442      *         smaller than {@code start} and no larger than
1443      *         {@code remaining()}
1444      *
1445      * @return  The new character buffer
1446      *
1447      * @throws  IndexOutOfBoundsException
1448      *          If the preconditions on {@code start} and {@code end}
1449      *          do not hold
1450      */
1451     public abstract CharBuffer subSequence(int start, int end);
1452 
1453 
1454     // --- Methods to support Appendable ---
1455 
1456     /**
1457      * Appends the specified character sequence  to this
1458      * buffer&nbsp;&nbsp;<i>(optional operation)</i>.
1459      *
1460      * <p> An invocation of this method of the form {@code dst.append(csq)}
1461      * behaves in exactly the same way as the invocation
1462      *
1463      * <pre>
1464      *     dst.put(csq.toString()) </pre>
1465      *
1466      * <p> Depending on the specification of {@code toString} for the
1467      * character sequence {@code csq}, the entire sequence may not be
1468      * appended.  For instance, invoking the {@link $Type$Buffer#toString()
1469      * toString} method of a character buffer will return a subsequence whose
1470      * content depends upon the buffer's position and limit.
1471      *
1472      * @param  csq
1473      *         The character sequence to append.  If {@code csq} is
1474      *         {@code null}, then the four characters {@code "null"} are
1475      *         appended to this character buffer.
1476      *
1477      * @return  This buffer
1478      *
1479      * @throws  BufferOverflowException
1480      *          If there is insufficient space in this buffer
1481      *
1482      * @throws  ReadOnlyBufferException
1483      *          If this buffer is read-only
1484      *
1485      * @since  1.5
1486      */
1487     public $Type$Buffer append(CharSequence csq) {
1488         if (csq == null)
1489             return put("null");
1490         else
1491             return put(csq.toString());
1492     }
1493 
1494     /**
1495      * Appends a subsequence of the  specified character sequence  to this
1496      * buffer&nbsp;&nbsp;<i>(optional operation)</i>.
1497      *
1498      * <p> An invocation of this method of the form {@code dst.append(csq, start,
1499      * end)} when {@code csq} is not {@code null}, behaves in exactly the
1500      * same way as the invocation
1501      *
1502      * <pre>
1503      *     dst.put(csq.subSequence(start, end).toString()) </pre>
1504      *
1505      * @param  csq
1506      *         The character sequence from which a subsequence will be
1507      *         appended.  If {@code csq} is {@code null}, then characters
1508      *         will be appended as if {@code csq} contained the four
1509      *         characters {@code "null"}.
1510      *
1511      * @return  This buffer
1512      *
1513      * @throws  BufferOverflowException
1514      *          If there is insufficient space in this buffer
1515      *
1516      * @throws  IndexOutOfBoundsException
1517      *          If {@code start} or {@code end} are negative, {@code start}
1518      *          is greater than {@code end}, or {@code end} is greater than
1519      *          {@code csq.length()}
1520      *
1521      * @throws  ReadOnlyBufferException
1522      *          If this buffer is read-only
1523      *
1524      * @since  1.5
1525      */
1526     public $Type$Buffer append(CharSequence csq, int start, int end) {
1527         CharSequence cs = (csq == null ? "null" : csq);
1528         return put(cs.subSequence(start, end).toString());
1529     }
1530 
1531     /**
1532      * Appends the specified $type$  to this
1533      * buffer&nbsp;&nbsp;<i>(optional operation)</i>.
1534      *
1535      * <p> An invocation of this method of the form {@code dst.append($x$)}
1536      * behaves in exactly the same way as the invocation
1537      *
1538      * <pre>
1539      *     dst.put($x$) </pre>
1540      *
1541      * @param  $x$
1542      *         The 16-bit $type$ to append
1543      *
1544      * @return  This buffer
1545      *
1546      * @throws  BufferOverflowException
1547      *          If there is insufficient space in this buffer
1548      *
1549      * @throws  ReadOnlyBufferException
1550      *          If this buffer is read-only
1551      *
1552      * @since  1.5
1553      */
1554     public $Type$Buffer append($type$ $x$) {
1555         return put($x$);
1556     }
1557 
1558 #end[char]
1559 
1560 
1561     // -- Other byte stuff: Access to binary data --
1562 
1563 #if[!byte]
1564 
1565     /**
1566      * Retrieves this buffer's byte order.
1567      *
1568      * <p> The byte order of $a$ $type$ buffer created by allocation or by
1569      * wrapping an existing {@code $type$} array is the {@link
1570      * ByteOrder#nativeOrder native order} of the underlying
1571      * hardware.  The byte order of $a$ $type$ buffer created as a <a
1572      * href="ByteBuffer.html#views">view</a> of a byte buffer is that of the
1573      * byte buffer at the moment that the view is created.  </p>
1574      *
1575      * @return  This buffer's byte order
1576      */
1577     public abstract ByteOrder order();
1578 
1579 #end[!byte]
1580 
1581 #if[byte]
1582 
1583     boolean bigEndian                                   // package-private
1584         = true;
1585     boolean nativeByteOrder                             // package-private
1586         = (Bits.byteOrder() == ByteOrder.BIG_ENDIAN);
1587 
1588     /**
1589      * Retrieves this buffer's byte order.
1590      *
1591      * <p> The byte order is used when reading or writing multibyte values, and
1592      * when creating buffers that are views of this byte buffer.  The order of
1593      * a newly-created byte buffer is always {@link ByteOrder#BIG_ENDIAN
1594      * BIG_ENDIAN}.  </p>
1595      *
1596      * @return  This buffer's byte order
1597      */
1598     public final ByteOrder order() {
1599         return bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
1600     }
1601 
1602     /**
1603      * Modifies this buffer's byte order.
1604      *
1605      * @param  bo
1606      *         The new byte order,
1607      *         either {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}
1608      *         or {@link ByteOrder#LITTLE_ENDIAN LITTLE_ENDIAN}
1609      *
1610      * @return  This buffer
1611      */
1612     public final $Type$Buffer order(ByteOrder bo) {
1613         bigEndian = (bo == ByteOrder.BIG_ENDIAN);
1614         nativeByteOrder =
1615             (bigEndian == (Bits.byteOrder() == ByteOrder.BIG_ENDIAN));
1616         return this;
1617     }
1618 
1619     /**
1620      * Returns the memory address, pointing to the byte at the given index,
1621      * modulus the given unit size.
1622      *
1623      * <p> A return value greater than zero indicates the address of the byte at
1624      * the index is misaligned for the unit size, and the value's quantity
1625      * indicates how much the index should be rounded up or down to locate a
1626      * byte at an aligned address.  Otherwise, a value of {@code 0} indicates
1627      * that the address of the byte at the index is aligned for the unit size.
1628      *
1629      * @apiNote
1630      * This method may be utilized to determine if unit size bytes from an
1631      * index can be accessed atomically, if supported by the native platform.
1632      *
1633      * @implNote
1634      * This implementation throws {@code UnsupportedOperationException} for
1635      * non-direct buffers when the given unit size is greater then {@code 8}.
1636      *
1637      * @param  index
1638      *         The index to query for alignment offset, must be non-negative, no
1639      *         upper bounds check is performed
1640      *
1641      * @param  unitSize
1642      *         The unit size in bytes, must be a power of {@code 2}
1643      *
1644      * @return  The indexed byte's memory address modulus the unit size
1645      *
1646      * @throws IllegalArgumentException
1647      *         If the index is negative or the unit size is not a power of
1648      *         {@code 2}
1649      *
1650      * @throws UnsupportedOperationException
1651      *         If the native platform does not guarantee stable alignment offset
1652      *         values for the given unit size when managing the memory regions
1653      *         of buffers of the same kind as this buffer (direct or
1654      *         non-direct).  For example, if garbage collection would result
1655      *         in the moving of a memory region covered by a non-direct buffer
1656      *         from one location to another and both locations have different
1657      *         alignment characteristics.
1658      *
1659      * @see #alignedSlice(int)
1660      * @since 9
1661      */
1662     public final int alignmentOffset(int index, int unitSize) {
1663         if (index < 0)
1664             throw new IllegalArgumentException("Index less than zero: " + index);
1665         if (unitSize < 1 || (unitSize & (unitSize - 1)) != 0)
1666             throw new IllegalArgumentException("Unit size not a power of two: " + unitSize);
1667         if (unitSize > 8 && !isDirect())
1668             throw new UnsupportedOperationException("Unit size unsupported for non-direct buffers: " + unitSize);
1669 
1670         return (int) ((address + index) % unitSize);
1671     }
1672 
1673     /**
1674      * Creates a new byte buffer whose content is a shared and aligned
1675      * subsequence of this buffer's content.
1676      *
1677      * <p> The content of the new buffer will start at this buffer's current
1678      * position rounded up to the index of the nearest aligned byte for the
1679      * given unit size, and end at this buffer's limit rounded down to the index
1680      * of the nearest aligned byte for the given unit size.
1681      * If rounding results in out-of-bound values then the new buffer's capacity
1682      * and limit will be zero.  If rounding is within bounds the following
1683      * expressions will be true for a new buffer {@code nb} and unit size
1684      * {@code unitSize}:
1685      * <pre>{@code
1686      * nb.alignmentOffset(0, unitSize) == 0
1687      * nb.alignmentOffset(nb.limit(), unitSize) == 0
1688      * }</pre>
1689      *
1690      * <p> Changes to this buffer's content will be visible in the new
1691      * buffer, and vice versa; the two buffers' position, limit, and mark
1692      * values will be independent.
1693      *
1694      * <p> The new buffer's position will be zero, its capacity and its limit
1695      * will be the number of bytes remaining in this buffer or fewer subject to
1696      * alignment, its mark will be undefined, and its byte order will be
1697      * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN}.
1698      *
1699      * The new buffer will be direct if, and only if, this buffer is direct, and
1700      * it will be read-only if, and only if, this buffer is read-only.  </p>
1701      *
1702      * @apiNote
1703      * This method may be utilized to create a new buffer where unit size bytes
1704      * from index, that is a multiple of the unit size, may be accessed
1705      * atomically, if supported by the native platform.
1706      *
1707      * @implNote
1708      * This implementation throws {@code UnsupportedOperationException} for
1709      * non-direct buffers when the given unit size is greater then {@code 8}.
1710      *
1711      * @param  unitSize
1712      *         The unit size in bytes, must be a power of {@code 2}
1713      *
1714      * @return  The new byte buffer
1715      *
1716      * @throws IllegalArgumentException
1717      *         If the unit size not a power of {@code 2}
1718      *
1719      * @throws UnsupportedOperationException
1720      *         If the native platform does not guarantee stable aligned slices
1721      *         for the given unit size when managing the memory regions
1722      *         of buffers of the same kind as this buffer (direct or
1723      *         non-direct).  For example, if garbage collection would result
1724      *         in the moving of a memory region covered by a non-direct buffer
1725      *         from one location to another and both locations have different
1726      *         alignment characteristics.
1727      *
1728      * @see #alignmentOffset(int, int)
1729      * @see #slice()
1730      * @since 9
1731      */
1732     public final ByteBuffer alignedSlice(int unitSize) {
1733         int pos = position();
1734         int lim = limit();
1735 
1736         int pos_mod = alignmentOffset(pos, unitSize);
1737         int lim_mod = alignmentOffset(lim, unitSize);
1738 
1739         // Round up the position to align with unit size
1740         int aligned_pos = (pos_mod > 0)
1741             ? pos + (unitSize - pos_mod)
1742             : pos;
1743 
1744         // Round down the limit to align with unit size
1745         int aligned_lim = lim - lim_mod;
1746 
1747         if (aligned_pos > lim || aligned_lim < pos) {
1748             aligned_pos = aligned_lim = pos;
1749         }
1750 
1751         return slice(aligned_pos, aligned_lim);
1752     }
1753 
1754     abstract ByteBuffer slice(int pos, int lim);
1755 
1756     // Unchecked accessors, for use by ByteBufferAs-X-Buffer classes
1757     //
1758     abstract byte _get(int i);                          // package-private
1759     abstract void _put(int i, byte b);                  // package-private
1760 
1761     // #BIN
1762     //
1763     // Binary-data access methods  for short, char, int, long, float,
1764     // and double will be inserted here
1765 
1766 #end[byte]
1767 
1768 #if[streamableType]
1769 
1770 #if[char]
1771     @Override
1772 #end[char]
1773     public $Streamtype$Stream $type$s() {
1774         return StreamSupport.$streamtype$Stream(() -> new $Type$BufferSpliterator(this),
1775             Buffer.SPLITERATOR_CHARACTERISTICS, false);
1776     }
1777 
1778 #end[streamableType]
1779 
1780 }