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