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