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