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