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