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