1 /* 2 * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.nio; 27 28 import jdk.internal.HotSpotIntrinsicCandidate; 29 import jdk.internal.misc.JavaNioAccess; 30 import jdk.internal.misc.SharedSecrets; 31 import jdk.internal.misc.Unsafe; 32 33 import java.util.Spliterator; 34 35 /** 36 * A container for data of a specific primitive type. 37 * 38 * <p> A buffer is a linear, finite sequence of elements of a specific 39 * primitive type. Aside from its content, the essential properties of a 40 * buffer are its capacity, limit, and position: </p> 41 * 42 * <blockquote> 43 * 44 * <p> A buffer's <i>capacity</i> is the number of elements it contains. The 45 * capacity of a buffer is never negative and never changes. </p> 46 * 47 * <p> A buffer's <i>limit</i> is the index of the first element that should 48 * not be read or written. A buffer's limit is never negative and is never 49 * greater than its capacity. </p> 50 * 51 * <p> A buffer's <i>position</i> is the index of the next element to be 52 * read or written. A buffer's position is never negative and is never 53 * greater than its limit. </p> 54 * 55 * </blockquote> 56 * 57 * <p> There is one subclass of this class for each non-boolean primitive type. 58 * 59 * 60 * <h2> Transferring data </h2> 61 * 62 * <p> Each subclass of this class defines two categories of <i>get</i> and 63 * <i>put</i> operations: </p> 64 * 65 * <blockquote> 66 * 67 * <p> <i>Relative</i> operations read or write one or more elements starting 68 * at the current position and then increment the position by the number of 69 * elements transferred. If the requested transfer exceeds the limit then a 70 * relative <i>get</i> operation throws a {@link BufferUnderflowException} 71 * and a relative <i>put</i> operation throws a {@link 72 * BufferOverflowException}; in either case, no data is transferred. </p> 73 * 74 * <p> <i>Absolute</i> operations take an explicit element index and do not 75 * affect the position. Absolute <i>get</i> and <i>put</i> operations throw 76 * an {@link IndexOutOfBoundsException} if the index argument exceeds the 77 * limit. </p> 78 * 79 * </blockquote> 80 * 81 * <p> Data may also, of course, be transferred in to or out of a buffer by the 82 * I/O operations of an appropriate channel, which are always relative to the 83 * current position. 84 * 85 * 86 * <h2> Marking and resetting </h2> 87 * 88 * <p> A buffer's <i>mark</i> is the index to which its position will be reset 89 * when the {@link #reset reset} method is invoked. The mark is not always 90 * defined, but when it is defined it is never negative and is never greater 91 * than the position. If the mark is defined then it is discarded when the 92 * position or the limit is adjusted to a value smaller than the mark. If the 93 * mark is not defined then invoking the {@link #reset reset} method causes an 94 * {@link InvalidMarkException} to be thrown. 95 * 96 * 97 * <h2> Invariants </h2> 98 * 99 * <p> The following invariant holds for the mark, position, limit, and 100 * capacity values: 101 * 102 * <blockquote> 103 * {@code 0} {@code <=} 104 * <i>mark</i> {@code <=} 105 * <i>position</i> {@code <=} 106 * <i>limit</i> {@code <=} 107 * <i>capacity</i> 108 * </blockquote> 109 * 110 * <p> A newly-created buffer always has a position of zero and a mark that is 111 * undefined. The initial limit may be zero, or it may be some other value 112 * that depends upon the type of the buffer and the manner in which it is 113 * constructed. Each element of a newly-allocated buffer is initialized 114 * to zero. 115 * 116 * 117 * <h2> Additional operations </h2> 118 * 119 * <p> In addition to methods for accessing the position, limit, and capacity 120 * values and for marking and resetting, this class also defines the following 121 * operations upon buffers: 122 * 123 * <ul> 124 * 125 * <li><p> {@link #clear} makes a buffer ready for a new sequence of 126 * channel-read or relative <i>put</i> operations: It sets the limit to the 127 * capacity and the position to zero. </p></li> 128 * 129 * <li><p> {@link #flip} makes a buffer ready for a new sequence of 130 * channel-write or relative <i>get</i> operations: It sets the limit to the 131 * current position and then sets the position to zero. </p></li> 132 * 133 * <li><p> {@link #rewind} makes a buffer ready for re-reading the data that 134 * it already contains: It leaves the limit unchanged and sets the position 135 * to zero. </p></li> 136 * 137 * <li><p> {@link #slice} creates a subsequence of a buffer: It leaves the 138 * limit and the position unchanged. </p></li> 139 * 140 * <li><p> {@link #duplicate} creates a shallow copy of a buffer: It leaves 141 * the limit and the position unchanged. </p></li> 142 * 143 * </ul> 144 * 145 * 146 * <h2> Read-only buffers </h2> 147 * 148 * <p> Every buffer is readable, but not every buffer is writable. The 149 * mutation methods of each buffer class are specified as <i>optional 150 * operations</i> that will throw a {@link ReadOnlyBufferException} when 151 * invoked upon a read-only buffer. A read-only buffer does not allow its 152 * content to be changed, but its mark, position, and limit values are mutable. 153 * Whether or not a buffer is read-only may be determined by invoking its 154 * {@link #isReadOnly isReadOnly} method. 155 * 156 * 157 * <h2> Thread safety </h2> 158 * 159 * <p> Buffers are not safe for use by multiple concurrent threads. If a 160 * buffer is to be used by more than one thread then access to the buffer 161 * should be controlled by appropriate synchronization. 162 * 163 * 164 * <h2> Invocation chaining </h2> 165 * 166 * <p> Methods in this class that do not otherwise have a value to return are 167 * specified to return the buffer upon which they are invoked. This allows 168 * method invocations to be chained; for example, the sequence of statements 169 * 170 * <blockquote><pre> 171 * b.flip(); 172 * b.position(23); 173 * b.limit(42);</pre></blockquote> 174 * 175 * can be replaced by the single, more compact statement 176 * 177 * <blockquote><pre> 178 * b.flip().position(23).limit(42);</pre></blockquote> 179 * 180 * 181 * @author Mark Reinhold 182 * @author JSR-51 Expert Group 183 * @since 1.4 184 */ 185 186 public abstract class Buffer { 187 // Cached unsafe-access object 188 static final Unsafe UNSAFE = Unsafe.getUnsafe(); 189 190 /** 191 * The characteristics of Spliterators that traverse and split elements 192 * maintained in Buffers. 193 */ 194 static final int SPLITERATOR_CHARACTERISTICS = 195 Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED; 196 197 // Invariants: mark <= position <= limit <= capacity 198 private int mark = -1; 199 private int position = 0; 200 private int limit; 201 private int capacity; 202 203 // Used by heap byte buffers or direct buffers with Unsafe access 204 // For heap byte buffers this field will be the address relative to the 205 // array base address and offset into that array. The address might 206 // not align on a word boundary for slices, nor align at a long word 207 // (8 byte) boundary for byte[] allocations on 32-bit systems. 208 // For direct buffers it is the start address of the memory region. The 209 // address might not align on a word boundary for slices, nor when created 210 // using JNI, see NewDirectByteBuffer(void*, long). 211 // Should ideally be declared final 212 // NOTE: hoisted here for speed in JNI GetDirectBufferAddress 213 long address; 214 215 // Creates a new buffer with the given mark, position, limit, and capacity, 216 // after checking invariants. 217 // 218 Buffer(int mark, int pos, int lim, int cap) { // package-private 219 if (cap < 0) 220 throw createCapacityException(cap); 221 this.capacity = cap; 222 limit(lim); 223 position(pos); 224 if (mark >= 0) { 225 if (mark > pos) 226 throw new IllegalArgumentException("mark > position: (" 227 + mark + " > " + pos + ")"); 228 this.mark = mark; 229 } 230 } 231 232 /** 233 * Returns an {@code IllegalArgumentException} indicating that the source 234 * and target are the same {@code Buffer}. Intended for use in 235 * {@code put(src)} when the parameter is the {@code Buffer} on which the 236 * method is being invoked. 237 * 238 * @return IllegalArgumentException 239 * With a message indicating equal source and target buffers 240 */ 241 static IllegalArgumentException createSameBufferException() { 242 return new IllegalArgumentException("The source buffer is this buffer"); 243 } 244 245 /** 246 * Verify that the capacity is nonnegative. 247 * 248 * @param capacity 249 * The new buffer's capacity, in $type$s 250 * 251 * @throws IllegalArgumentException 252 * If the {@code capacity} is a negative integer 253 */ 254 static IllegalArgumentException createCapacityException(int capacity) { 255 assert capacity < 0 : "capacity expected to be negative"; 256 return new IllegalArgumentException("capacity < 0: (" 257 + capacity + " < 0)"); 258 } 259 260 /** 261 * Returns this buffer's capacity. 262 * 263 * @return The capacity of this buffer 264 */ 265 public final int capacity() { 266 return capacity; 267 } 268 269 /** 270 * Returns this buffer's position. 271 * 272 * @return The position of this buffer 273 */ 274 public final int position() { 275 return position; 276 } 277 278 /** 279 * Sets this buffer's position. If the mark is defined and larger than the 280 * new position then it is discarded. 281 * 282 * @param newPosition 283 * The new position value; must be non-negative 284 * and no larger than the current limit 285 * 286 * @return This buffer 287 * 288 * @throws IllegalArgumentException 289 * If the preconditions on {@code newPosition} do not hold 290 */ 291 public Buffer position(int newPosition) { 292 if (newPosition > limit | newPosition < 0) 293 throw createPositionException(newPosition); 294 position = newPosition; 295 if (mark > position) mark = -1; 296 return this; 297 } 298 299 /** 300 * Verify that {@code 0 < newPosition <= limit} 301 * 302 * @param newPosition 303 * The new position value 304 * 305 * @throws IllegalArgumentException 306 * If the specified position is out of bounds. 307 */ 308 private IllegalArgumentException createPositionException(int newPosition) { 309 String msg = null; 310 311 if (newPosition > limit) { 312 msg = "newPosition > limit: (" + newPosition + " > " + limit + ")"; 313 } else { // assume negative 314 assert newPosition < 0 : "newPosition expected to be negative"; 315 msg = "newPosition < 0: (" + newPosition + " < 0)"; 316 } 317 318 return new IllegalArgumentException(msg); 319 } 320 321 /** 322 * Returns this buffer's limit. 323 * 324 * @return The limit of this buffer 325 */ 326 public final int limit() { 327 return limit; 328 } 329 330 /** 331 * Sets this buffer's limit. If the position is larger than the new limit 332 * then it is set to the new limit. If the mark is defined and larger than 333 * the new limit then it is discarded. 334 * 335 * @param newLimit 336 * The new limit value; must be non-negative 337 * and no larger than this buffer's capacity 338 * 339 * @return This buffer 340 * 341 * @throws IllegalArgumentException 342 * If the preconditions on {@code newLimit} do not hold 343 */ 344 public Buffer limit(int newLimit) { 345 if (newLimit > capacity | newLimit < 0) 346 throw createLimitException(newLimit); 347 limit = newLimit; 348 if (position > limit) position = limit; 349 if (mark > limit) mark = -1; 350 return this; 351 } 352 353 /** 354 * Verify that {@code 0 < newLimit <= capacity} 355 * 356 * @param newLimit 357 * The new limit value 358 * 359 * @throws IllegalArgumentException 360 * If the specified limit is out of bounds. 361 */ 362 private IllegalArgumentException createLimitException(int newLimit) { 363 String msg = null; 364 365 if (newLimit > capacity) { 366 msg = "newLimit > capacity: (" + newLimit + " > " + capacity + ")"; 367 } else { // assume negative 368 assert newLimit < 0 : "newLimit expected to be negative"; 369 msg = "newLimit < 0: (" + newLimit + " < 0)"; 370 } 371 372 return new IllegalArgumentException(msg); 373 } 374 375 /** 376 * Sets this buffer's mark at its position. 377 * 378 * @return This buffer 379 */ 380 public Buffer mark() { 381 mark = position; 382 return this; 383 } 384 385 /** 386 * Resets this buffer's position to the previously-marked position. 387 * 388 * <p> Invoking this method neither changes nor discards the mark's 389 * value. </p> 390 * 391 * @return This buffer 392 * 393 * @throws InvalidMarkException 394 * If the mark has not been set 395 */ 396 public Buffer reset() { 397 int m = mark; 398 if (m < 0) 399 throw new InvalidMarkException(); 400 position = m; 401 return this; 402 } 403 404 /** 405 * Clears this buffer. The position is set to zero, the limit is set to 406 * the capacity, and the mark is discarded. 407 * 408 * <p> Invoke this method before using a sequence of channel-read or 409 * <i>put</i> operations to fill this buffer. For example: 410 * 411 * <blockquote><pre> 412 * buf.clear(); // Prepare buffer for reading 413 * in.read(buf); // Read data</pre></blockquote> 414 * 415 * <p> This method does not actually erase the data in the buffer, but it 416 * is named as if it did because it will most often be used in situations 417 * in which that might as well be the case. </p> 418 * 419 * @return This buffer 420 */ 421 public Buffer clear() { 422 position = 0; 423 limit = capacity; 424 mark = -1; 425 return this; 426 } 427 428 /** 429 * Flips this buffer. The limit is set to the current position and then 430 * the position is set to zero. If the mark is defined then it is 431 * discarded. 432 * 433 * <p> After a sequence of channel-read or <i>put</i> operations, invoke 434 * this method to prepare for a sequence of channel-write or relative 435 * <i>get</i> operations. For example: 436 * 437 * <blockquote><pre> 438 * buf.put(magic); // Prepend header 439 * in.read(buf); // Read data into rest of buffer 440 * buf.flip(); // Flip buffer 441 * out.write(buf); // Write header + data to channel</pre></blockquote> 442 * 443 * <p> This method is often used in conjunction with the {@link 444 * java.nio.ByteBuffer#compact compact} method when transferring data from 445 * one place to another. </p> 446 * 447 * @return This buffer 448 */ 449 public Buffer flip() { 450 limit = position; 451 position = 0; 452 mark = -1; 453 return this; 454 } 455 456 /** 457 * Rewinds this buffer. The position is set to zero and the mark is 458 * discarded. 459 * 460 * <p> Invoke this method before a sequence of channel-write or <i>get</i> 461 * operations, assuming that the limit has already been set 462 * appropriately. For example: 463 * 464 * <blockquote><pre> 465 * out.write(buf); // Write remaining data 466 * buf.rewind(); // Rewind buffer 467 * buf.get(array); // Copy data into array</pre></blockquote> 468 * 469 * @return This buffer 470 */ 471 public Buffer rewind() { 472 position = 0; 473 mark = -1; 474 return this; 475 } 476 477 /** 478 * Returns the number of elements between the current position and the 479 * limit. 480 * 481 * @return The number of elements remaining in this buffer 482 */ 483 public final int remaining() { 484 return limit - position; 485 } 486 487 /** 488 * Tells whether there are any elements between the current position and 489 * the limit. 490 * 491 * @return {@code true} if, and only if, there is at least one element 492 * remaining in this buffer 493 */ 494 public final boolean hasRemaining() { 495 return position < limit; 496 } 497 498 /** 499 * Tells whether or not this buffer is read-only. 500 * 501 * @return {@code true} if, and only if, this buffer is read-only 502 */ 503 public abstract boolean isReadOnly(); 504 505 /** 506 * Tells whether or not this buffer is backed by an accessible 507 * array. 508 * 509 * <p> If this method returns {@code true} then the {@link #array() array} 510 * and {@link #arrayOffset() arrayOffset} methods may safely be invoked. 511 * </p> 512 * 513 * @return {@code true} if, and only if, this buffer 514 * is backed by an array and is not read-only 515 * 516 * @since 1.6 517 */ 518 public abstract boolean hasArray(); 519 520 /** 521 * Returns the array that backs this 522 * buffer <i>(optional operation)</i>. 523 * 524 * <p> This method is intended to allow array-backed buffers to be 525 * passed to native code more efficiently. Concrete subclasses 526 * provide more strongly-typed return values for this method. 527 * 528 * <p> Modifications to this buffer's content will cause the returned 529 * array's content to be modified, and vice versa. 530 * 531 * <p> Invoke the {@link #hasArray hasArray} method before invoking this 532 * method in order to ensure that this buffer has an accessible backing 533 * array. </p> 534 * 535 * @return The array that backs this buffer 536 * 537 * @throws ReadOnlyBufferException 538 * If this buffer is backed by an array but is read-only 539 * 540 * @throws UnsupportedOperationException 541 * If this buffer is not backed by an accessible array 542 * 543 * @since 1.6 544 */ 545 public abstract Object array(); 546 547 /** 548 * Returns the offset within this buffer's backing array of the first 549 * element of the buffer <i>(optional operation)</i>. 550 * 551 * <p> If this buffer is backed by an array then buffer position <i>p</i> 552 * corresponds to array index <i>p</i> + {@code arrayOffset()}. 553 * 554 * <p> Invoke the {@link #hasArray hasArray} method before invoking this 555 * method in order to ensure that this buffer has an accessible backing 556 * array. </p> 557 * 558 * @return The offset within this buffer's array 559 * of the first element of the buffer 560 * 561 * @throws ReadOnlyBufferException 562 * If this buffer is backed by an array but is read-only 563 * 564 * @throws UnsupportedOperationException 565 * If this buffer is not backed by an accessible array 566 * 567 * @since 1.6 568 */ 569 public abstract int arrayOffset(); 570 571 /** 572 * Tells whether or not this buffer is 573 * <a href="ByteBuffer.html#direct"><i>direct</i></a>. 574 * 575 * @return {@code true} if, and only if, this buffer is direct 576 * 577 * @since 1.6 578 */ 579 public abstract boolean isDirect(); 580 581 /** 582 * Creates a new buffer whose content is a shared subsequence of 583 * this buffer's content. 584 * 585 * <p> The content of the new buffer will start at this buffer's current 586 * position. Changes to this buffer's content will be visible in the new 587 * buffer, and vice versa; the two buffers' position, limit, and mark 588 * values will be independent. 589 * 590 * <p> The new buffer's position will be zero, its capacity and its limit 591 * will be the number of elements remaining in this buffer, its mark will be 592 * undefined. The new buffer will be direct if, and only if, this buffer is 593 * direct, and it will be read-only if, and only if, this buffer is 594 * read-only. </p> 595 * 596 * @return The new buffer 597 * 598 * @since 9 599 */ 600 public abstract Buffer slice(); 601 602 /** 603 * Creates a new buffer that shares this buffer's content. 604 * 605 * <p> The content of the new buffer will be that of this buffer. Changes 606 * to this buffer's content will be visible in the new buffer, and vice 607 * versa; the two buffers' position, limit, and mark values will be 608 * independent. 609 * 610 * <p> The new buffer's capacity, limit, position and mark values will be 611 * identical to those of this buffer. The new buffer will be direct if, and 612 * only if, this buffer is direct, and it will be read-only if, and only if, 613 * this buffer is read-only. </p> 614 * 615 * @return The new buffer 616 * 617 * @since 9 618 */ 619 public abstract Buffer duplicate(); 620 621 622 // -- Package-private methods for bounds checking, etc. -- 623 624 /** 625 * 626 * @return the base reference, paired with the address 627 * field, which in combination can be used for unsafe access into a heap 628 * buffer or direct byte buffer (and views of). 629 */ 630 abstract Object base(); 631 632 /** 633 * Checks the current position against the limit, throwing a {@link 634 * BufferUnderflowException} if it is not smaller than the limit, and then 635 * increments the position. 636 * 637 * @return The current position value, before it is incremented 638 */ 639 final int nextGetIndex() { // package-private 640 if (position >= limit) 641 throw new BufferUnderflowException(); 642 return position++; 643 } 644 645 final int nextGetIndex(int nb) { // package-private 646 if (limit - position < nb) 647 throw new BufferUnderflowException(); 648 int p = position; 649 position += nb; 650 return p; 651 } 652 653 /** 654 * Checks the current position against the limit, throwing a {@link 655 * BufferOverflowException} if it is not smaller than the limit, and then 656 * increments the position. 657 * 658 * @return The current position value, before it is incremented 659 */ 660 final int nextPutIndex() { // package-private 661 if (position >= limit) 662 throw new BufferOverflowException(); 663 return position++; 664 } 665 666 final int nextPutIndex(int nb) { // package-private 667 if (limit - position < nb) 668 throw new BufferOverflowException(); 669 int p = position; 670 position += nb; 671 return p; 672 } 673 674 /** 675 * Checks the given index against the limit, throwing an {@link 676 * IndexOutOfBoundsException} if it is not smaller than the limit 677 * or is smaller than zero. 678 */ 679 @HotSpotIntrinsicCandidate 680 final int checkIndex(int i) { // package-private 681 if ((i < 0) || (i >= limit)) 682 throw new IndexOutOfBoundsException(); 683 return i; 684 } 685 686 final int checkIndex(int i, int nb) { // package-private 687 if ((i < 0) || (nb > limit - i)) 688 throw new IndexOutOfBoundsException(); 689 return i; 690 } 691 692 final int markValue() { // package-private 693 return mark; 694 } 695 696 final void truncate() { // package-private 697 mark = -1; 698 position = 0; 699 limit = 0; 700 capacity = 0; 701 } 702 703 final void discardMark() { // package-private 704 mark = -1; 705 } 706 707 static void checkBounds(int off, int len, int size) { // package-private 708 if ((off | len | (off + len) | (size - (off + len))) < 0) 709 throw new IndexOutOfBoundsException(); 710 } 711 712 static { 713 // setup access to this package in SharedSecrets 714 SharedSecrets.setJavaNioAccess( 715 new JavaNioAccess() { 716 @Override 717 public JavaNioAccess.BufferPool getDirectBufferPool() { 718 return Bits.BUFFER_POOL; 719 } 720 @Override 721 public ByteBuffer newDirectByteBuffer(long addr, int cap, Object ob) { 722 return new DirectByteBuffer(addr, cap, ob); 723 } 724 @Override 725 public void truncate(Buffer buf) { 726 buf.truncate(); 727 } 728 }); 729 } 730 731 }