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