Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/nio/Buffer.java
38829 views
/*1* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio;2627import java.util.Spliterator;2829/**30* A container for data of a specific primitive type.31*32* <p> A buffer is a linear, finite sequence of elements of a specific33* primitive type. Aside from its content, the essential properties of a34* buffer are its capacity, limit, and position: </p>35*36* <blockquote>37*38* <p> A buffer's <i>capacity</i> is the number of elements it contains. The39* capacity of a buffer is never negative and never changes. </p>40*41* <p> A buffer's <i>limit</i> is the index of the first element that should42* not be read or written. A buffer's limit is never negative and is never43* greater than its capacity. </p>44*45* <p> A buffer's <i>position</i> is the index of the next element to be46* read or written. A buffer's position is never negative and is never47* greater than its limit. </p>48*49* </blockquote>50*51* <p> There is one subclass of this class for each non-boolean primitive type.52*53*54* <h2> Transferring data </h2>55*56* <p> Each subclass of this class defines two categories of <i>get</i> and57* <i>put</i> operations: </p>58*59* <blockquote>60*61* <p> <i>Relative</i> operations read or write one or more elements starting62* at the current position and then increment the position by the number of63* elements transferred. If the requested transfer exceeds the limit then a64* relative <i>get</i> operation throws a {@link BufferUnderflowException}65* and a relative <i>put</i> operation throws a {@link66* BufferOverflowException}; in either case, no data is transferred. </p>67*68* <p> <i>Absolute</i> operations take an explicit element index and do not69* affect the position. Absolute <i>get</i> and <i>put</i> operations throw70* an {@link IndexOutOfBoundsException} if the index argument exceeds the71* limit. </p>72*73* </blockquote>74*75* <p> Data may also, of course, be transferred in to or out of a buffer by the76* I/O operations of an appropriate channel, which are always relative to the77* current position.78*79*80* <h2> Marking and resetting </h2>81*82* <p> A buffer's <i>mark</i> is the index to which its position will be reset83* when the {@link #reset reset} method is invoked. The mark is not always84* defined, but when it is defined it is never negative and is never greater85* than the position. If the mark is defined then it is discarded when the86* position or the limit is adjusted to a value smaller than the mark. If the87* mark is not defined then invoking the {@link #reset reset} method causes an88* {@link InvalidMarkException} to be thrown.89*90*91* <h2> Invariants </h2>92*93* <p> The following invariant holds for the mark, position, limit, and94* capacity values:95*96* <blockquote>97* <tt>0</tt> <tt><=</tt>98* <i>mark</i> <tt><=</tt>99* <i>position</i> <tt><=</tt>100* <i>limit</i> <tt><=</tt>101* <i>capacity</i>102* </blockquote>103*104* <p> A newly-created buffer always has a position of zero and a mark that is105* undefined. The initial limit may be zero, or it may be some other value106* that depends upon the type of the buffer and the manner in which it is107* constructed. Each element of a newly-allocated buffer is initialized108* to zero.109*110*111* <h2> Clearing, flipping, and rewinding </h2>112*113* <p> In addition to methods for accessing the position, limit, and capacity114* values and for marking and resetting, this class also defines the following115* operations upon buffers:116*117* <ul>118*119* <li><p> {@link #clear} makes a buffer ready for a new sequence of120* channel-read or relative <i>put</i> operations: It sets the limit to the121* capacity and the position to zero. </p></li>122*123* <li><p> {@link #flip} makes a buffer ready for a new sequence of124* channel-write or relative <i>get</i> operations: It sets the limit to the125* current position and then sets the position to zero. </p></li>126*127* <li><p> {@link #rewind} makes a buffer ready for re-reading the data that128* it already contains: It leaves the limit unchanged and sets the position129* to zero. </p></li>130*131* </ul>132*133*134* <h2> Read-only buffers </h2>135*136* <p> Every buffer is readable, but not every buffer is writable. The137* mutation methods of each buffer class are specified as <i>optional138* operations</i> that will throw a {@link ReadOnlyBufferException} when139* invoked upon a read-only buffer. A read-only buffer does not allow its140* content to be changed, but its mark, position, and limit values are mutable.141* Whether or not a buffer is read-only may be determined by invoking its142* {@link #isReadOnly isReadOnly} method.143*144*145* <h2> Thread safety </h2>146*147* <p> Buffers are not safe for use by multiple concurrent threads. If a148* buffer is to be used by more than one thread then access to the buffer149* should be controlled by appropriate synchronization.150*151*152* <h2> Invocation chaining </h2>153*154* <p> Methods in this class that do not otherwise have a value to return are155* specified to return the buffer upon which they are invoked. This allows156* method invocations to be chained; for example, the sequence of statements157*158* <blockquote><pre>159* b.flip();160* b.position(23);161* b.limit(42);</pre></blockquote>162*163* can be replaced by the single, more compact statement164*165* <blockquote><pre>166* b.flip().position(23).limit(42);</pre></blockquote>167*168*169* @author Mark Reinhold170* @author JSR-51 Expert Group171* @since 1.4172*/173174public abstract class Buffer {175176/**177* The characteristics of Spliterators that traverse and split elements178* maintained in Buffers.179*/180static final int SPLITERATOR_CHARACTERISTICS =181Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED;182183// Invariants: mark <= position <= limit <= capacity184private int mark = -1;185private int position = 0;186private int limit;187private int capacity;188189// Used only by direct buffers190// NOTE: hoisted here for speed in JNI GetDirectBufferAddress191long address;192193// Creates a new buffer with the given mark, position, limit, and capacity,194// after checking invariants.195//196Buffer(int mark, int pos, int lim, int cap) { // package-private197if (cap < 0)198throw new IllegalArgumentException("Negative capacity: " + cap);199this.capacity = cap;200limit(lim);201position(pos);202if (mark >= 0) {203if (mark > pos)204throw new IllegalArgumentException("mark > position: ("205+ mark + " > " + pos + ")");206this.mark = mark;207}208}209210/**211* Returns this buffer's capacity.212*213* @return The capacity of this buffer214*/215public final int capacity() {216return capacity;217}218219/**220* Returns this buffer's position.221*222* @return The position of this buffer223*/224public final int position() {225return position;226}227228/**229* Sets this buffer's position. If the mark is defined and larger than the230* new position then it is discarded.231*232* @param newPosition233* The new position value; must be non-negative234* and no larger than the current limit235*236* @return This buffer237*238* @throws IllegalArgumentException239* If the preconditions on <tt>newPosition</tt> do not hold240*/241public final Buffer position(int newPosition) {242if ((newPosition > limit) || (newPosition < 0))243throw new IllegalArgumentException();244if (mark > newPosition) mark = -1;245position = newPosition;246return this;247}248249/**250* Returns this buffer's limit.251*252* @return The limit of this buffer253*/254public final int limit() {255return limit;256}257258/**259* Sets this buffer's limit. If the position is larger than the new limit260* then it is set to the new limit. If the mark is defined and larger than261* the new limit then it is discarded.262*263* @param newLimit264* The new limit value; must be non-negative265* and no larger than this buffer's capacity266*267* @return This buffer268*269* @throws IllegalArgumentException270* If the preconditions on <tt>newLimit</tt> do not hold271*/272public final Buffer limit(int newLimit) {273if ((newLimit > capacity) || (newLimit < 0))274throw new IllegalArgumentException();275limit = newLimit;276if (position > newLimit) position = newLimit;277if (mark > newLimit) mark = -1;278return this;279}280281/**282* Sets this buffer's mark at its position.283*284* @return This buffer285*/286public final Buffer mark() {287mark = position;288return this;289}290291/**292* Resets this buffer's position to the previously-marked position.293*294* <p> Invoking this method neither changes nor discards the mark's295* value. </p>296*297* @return This buffer298*299* @throws InvalidMarkException300* If the mark has not been set301*/302public final Buffer reset() {303int m = mark;304if (m < 0)305throw new InvalidMarkException();306position = m;307return this;308}309310/**311* Clears this buffer. The position is set to zero, the limit is set to312* the capacity, and the mark is discarded.313*314* <p> Invoke this method before using a sequence of channel-read or315* <i>put</i> operations to fill this buffer. For example:316*317* <blockquote><pre>318* buf.clear(); // Prepare buffer for reading319* in.read(buf); // Read data</pre></blockquote>320*321* <p> This method does not actually erase the data in the buffer, but it322* is named as if it did because it will most often be used in situations323* in which that might as well be the case. </p>324*325* @return This buffer326*/327public final Buffer clear() {328position = 0;329limit = capacity;330mark = -1;331return this;332}333334/**335* Flips this buffer. The limit is set to the current position and then336* the position is set to zero. If the mark is defined then it is337* discarded.338*339* <p> After a sequence of channel-read or <i>put</i> operations, invoke340* this method to prepare for a sequence of channel-write or relative341* <i>get</i> operations. For example:342*343* <blockquote><pre>344* buf.put(magic); // Prepend header345* in.read(buf); // Read data into rest of buffer346* buf.flip(); // Flip buffer347* out.write(buf); // Write header + data to channel</pre></blockquote>348*349* <p> This method is often used in conjunction with the {@link350* java.nio.ByteBuffer#compact compact} method when transferring data from351* one place to another. </p>352*353* @return This buffer354*/355public final Buffer flip() {356limit = position;357position = 0;358mark = -1;359return this;360}361362/**363* Rewinds this buffer. The position is set to zero and the mark is364* discarded.365*366* <p> Invoke this method before a sequence of channel-write or <i>get</i>367* operations, assuming that the limit has already been set368* appropriately. For example:369*370* <blockquote><pre>371* out.write(buf); // Write remaining data372* buf.rewind(); // Rewind buffer373* buf.get(array); // Copy data into array</pre></blockquote>374*375* @return This buffer376*/377public final Buffer rewind() {378position = 0;379mark = -1;380return this;381}382383/**384* Returns the number of elements between the current position and the385* limit.386*387* @return The number of elements remaining in this buffer388*/389public final int remaining() {390int rem = limit - position;391return rem > 0 ? rem : 0;392}393394/**395* Tells whether there are any elements between the current position and396* the limit.397*398* @return <tt>true</tt> if, and only if, there is at least one element399* remaining in this buffer400*/401public final boolean hasRemaining() {402return position < limit;403}404405/**406* Tells whether or not this buffer is read-only.407*408* @return <tt>true</tt> if, and only if, this buffer is read-only409*/410public abstract boolean isReadOnly();411412/**413* Tells whether or not this buffer is backed by an accessible414* array.415*416* <p> If this method returns <tt>true</tt> then the {@link #array() array}417* and {@link #arrayOffset() arrayOffset} methods may safely be invoked.418* </p>419*420* @return <tt>true</tt> if, and only if, this buffer421* is backed by an array and is not read-only422*423* @since 1.6424*/425public abstract boolean hasArray();426427/**428* Returns the array that backs this429* buffer <i>(optional operation)</i>.430*431* <p> This method is intended to allow array-backed buffers to be432* passed to native code more efficiently. Concrete subclasses433* provide more strongly-typed return values for this method.434*435* <p> Modifications to this buffer's content will cause the returned436* array's content to be modified, and vice versa.437*438* <p> Invoke the {@link #hasArray hasArray} method before invoking this439* method in order to ensure that this buffer has an accessible backing440* array. </p>441*442* @return The array that backs this buffer443*444* @throws ReadOnlyBufferException445* If this buffer is backed by an array but is read-only446*447* @throws UnsupportedOperationException448* If this buffer is not backed by an accessible array449*450* @since 1.6451*/452public abstract Object array();453454/**455* Returns the offset within this buffer's backing array of the first456* element of the buffer <i>(optional operation)</i>.457*458* <p> If this buffer is backed by an array then buffer position <i>p</i>459* corresponds to array index <i>p</i> + <tt>arrayOffset()</tt>.460*461* <p> Invoke the {@link #hasArray hasArray} method before invoking this462* method in order to ensure that this buffer has an accessible backing463* array. </p>464*465* @return The offset within this buffer's array466* of the first element of the buffer467*468* @throws ReadOnlyBufferException469* If this buffer is backed by an array but is read-only470*471* @throws UnsupportedOperationException472* If this buffer is not backed by an accessible array473*474* @since 1.6475*/476public abstract int arrayOffset();477478/**479* Tells whether or not this buffer is480* <a href="ByteBuffer.html#direct"><i>direct</i></a>.481*482* @return <tt>true</tt> if, and only if, this buffer is direct483*484* @since 1.6485*/486public abstract boolean isDirect();487488489// -- Package-private methods for bounds checking, etc. --490491/**492* Checks the current position against the limit, throwing a {@link493* BufferUnderflowException} if it is not smaller than the limit, and then494* increments the position.495*496* @return The current position value, before it is incremented497*/498final int nextGetIndex() { // package-private499int p = position;500if (p >= limit)501throw new BufferUnderflowException();502position = p + 1;503return p;504}505506final int nextGetIndex(int nb) { // package-private507int p = position;508if (limit - p < nb)509throw new BufferUnderflowException();510position = p + nb;511return p;512}513514/**515* Checks the current position against the limit, throwing a {@link516* BufferOverflowException} if it is not smaller than the limit, and then517* increments the position.518*519* @return The current position value, before it is incremented520*/521final int nextPutIndex() { // package-private522int p = position;523if (p >= limit)524throw new BufferOverflowException();525position = p + 1;526return p;527}528529final int nextPutIndex(int nb) { // package-private530int p = position;531if (limit - p < nb)532throw new BufferOverflowException();533position = p + nb;534return p;535}536537/**538* Checks the given index against the limit, throwing an {@link539* IndexOutOfBoundsException} if it is not smaller than the limit540* or is smaller than zero.541*/542final int checkIndex(int i) { // package-private543if ((i < 0) || (i >= limit))544throw new IndexOutOfBoundsException();545return i;546}547548final int checkIndex(int i, int nb) { // package-private549if ((i < 0) || (nb > limit - i))550throw new IndexOutOfBoundsException();551return i;552}553554final int markValue() { // package-private555return mark;556}557558final void truncate() { // package-private559mark = -1;560position = 0;561limit = 0;562capacity = 0;563}564565final void discardMark() { // package-private566mark = -1;567}568569static void checkBounds(int off, int len, int size) { // package-private570if ((off | len | (off + len) | (size - (off + len))) < 0)571throw new IndexOutOfBoundsException();572}573574}575576577