Interface NetworkBuffer
public sealed interface NetworkBuffer
A mutable byte buffer that reads and writes network protocol data through
NetworkBuffer.Types.
Buffers keep separate read and write indexes. They come in two flavors:
- Static buffers have no resize strategy, so writes past their capacity fail. They are created with
staticBuffer(long). - Resizable buffers grow when a write needs more room and are created with
resizableBuffer().
NetworkBuffer buffer = NetworkBuffer.resizableBuffer();
buffer.write(NetworkBuffer.INT, 42);
buffer.write(NetworkBuffer.STRING, "Hello");
int value = buffer.read(NetworkBuffer.INT);
String text = buffer.read(NetworkBuffer.STRING);
Custom Types with Templates:
record MyData(int id, String name) {
static final NetworkBuffer.Type<MyData> SERIALIZER = NetworkBufferTemplate.template(
NetworkBuffer.INT, MyData::id,
NetworkBuffer.STRING, MyData::name,
MyData::new);
}
MyData data = new MyData(1, "Test");
byte[] bytes = NetworkBuffer.makeArray(MyData.SERIALIZER, data);
NetworkBuffer buffer = NetworkBuffer.wrap(bytes, 0, bytes.length);
MyData value = buffer.read(MyData.SERIALIZER); // MyData[id=1, name=Test]
Buffers are not thread safe, because they track their read and write indexes.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic interfaceResize strategy for aNetworkBuffer, used when a write needs more room than the capacity.static interfaceConfigures and creates buffers, obtained frombuilder(long).static interfaceNetworkBuffer.Type<T extends @UnknownNullability Object>Reads and writes values ofTin aNetworkBuffer, so that reading returns the value that was written. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final NetworkBuffer.Type<BitSet> static final NetworkBuffer.Type<Point> static final NetworkBuffer.Type<Boolean> static final NetworkBuffer.Type<Byte> static final NetworkBuffer.Type<byte[]> static final NetworkBuffer.Type<Component> static final NetworkBuffer.Type<Direction> static final NetworkBuffer.Type<Double> static final NetworkBuffer.Type<Float> static final NetworkBuffer.Type<Instant> static final NetworkBuffer.Type<Integer> static final NetworkBuffer.Type<Component> static final NetworkBuffer.Type<Key> static final NetworkBuffer.Type<Long> static final NetworkBuffer.Type<long[]> static final NetworkBuffer.Type<Vec> static final NetworkBuffer.Type<BinaryTag> static final NetworkBuffer.Type<CompoundBinaryTag> static final NetworkBuffer.Type<@Nullable Point> static final NetworkBuffer.Type<@Nullable Component> static final NetworkBuffer.Type<@Nullable Integer> static final NetworkBuffer.Type<Pos> static final NetworkBuffer.Type<EntityPose> static final NetworkBuffer.Type<PublicKey> static final NetworkBuffer.Type<float[]> static final NetworkBuffer.Type<byte[]> static final NetworkBuffer.Type<double[]> static final NetworkBuffer.Type<float[]> static final NetworkBuffer.Type<int[]> static final NetworkBuffer.Type<long[]> static final NetworkBuffer.Type<short[]> static final NetworkBuffer.Type<Short> static final NetworkBuffer.Type<String> static final NetworkBuffer.Type<String> static final NetworkBuffer.Type<String> static final NetworkBuffer.Type<Unit> static final NetworkBuffer.Type<Short> static final NetworkBuffer.Type<Long> static final NetworkBuffer.Type<Integer> static final NetworkBuffer.Type<BinaryTag> static final NetworkBuffer.Type<CompoundBinaryTag> static final NetworkBuffer.Type<UUID> static final NetworkBuffer.Type<Integer> static final NetworkBuffer.Type<Integer> static final NetworkBuffer.Type<int[]> static final NetworkBuffer.Type<Long> static final NetworkBuffer.Type<long[]> static final NetworkBuffer.Type<Point> static final NetworkBuffer.Type<Point> static final NetworkBuffer.Type<Point> static final NetworkBuffer.Type<Point> -
Method Summary
Modifier and TypeMethodDescriptionlongadvanceRead(long length) Moves the read index forward bylength.longadvanceWrite(long length) Moves the write index forward bylength.static NetworkBuffer.Builderbuilder(long size) Creates a builder for a buffer with an initial capacity ofsizebytes.longcapacity()Returns the size of the memory backing this buffer.voidEncrypts or decryptslengthbytes starting atstartin place withcipher.clear()Sets the read and write indexes to 0.voidcompact()Moves the readable bytes to the start of the buffer and lowers both indexes by the old read index.longcompress(long start, long length, NetworkBuffer output) Compresseslengthbytes starting atstartwith aDeflaterintooutputat its write index, and advances the write index ofoutput.default NetworkBuffercopy(long index, long length) Copieslengthbytes starting atindexinto a new buffer with the current indexes of this buffer.copy(long index, long length, long readIndex, long writeIndex) Copieslengthbytes starting atindexinto a new buffer with the given indexes.static voidcopy(NetworkBuffer srcBuffer, long srcOffset, NetworkBuffer dstBuffer, long dstOffset, long length) Copieslengthbytes fromsrcBufferatsrcOffsettodstBufferatdstOffset, ignoring the read and write indexes of both buffers.voidcopyTo(long srcOffset, byte[] dest, int destOffset, int length) Copieslengthbytes starting atsrcOffsetintodest, ignoring the read and write indexes.voidcopyTo(long srcOffset, MemorySegment dest, long destOffset, long length) Copieslengthbytes starting atsrcOffsetintodest, ignoring the read and write indexes.longdecompress(long start, long length, NetworkBuffer output) Decompresseslengthbytes starting atstartwith anInflaterintooutputat its write index, and advances the write index ofoutput.static <L,R> NetworkBuffer.Type <Either<L, R>> Either(NetworkBuffer.Type<L> left, NetworkBuffer.Type<R> right) voidensureReadable(long length) Ensures that at leastlengthbytes are readable, as counted byreadableBytes().voidensureWritable(long length) Ensures that at leastlengthbytes can be written at thewriteIndex(), resizing the buffer with its resize strategy when needed.static <E extends Enum<E>>
NetworkBuffer.Type<E> Creates a type for the constants of an enum, encoded as aVAR_INTof the ordinal.static <E extends Enum<E>>
NetworkBuffer.Type<EnumSet<E>> Creates a type for a set of enum constants, encoded as aFixedBitSet(int)with one bit per constant in ordinal order.static booleanequals(NetworkBuffer buffer1, NetworkBuffer buffer2) Checks whether two buffers have the same capacity and the same bytes across it, ignoring their read and write indexes.byte[]extractBytes(Consumer<? super NetworkBuffer> extractor) Runsextractoron this buffer and returns a copy of the bytes it read, from thereadIndex()before the call to the one after it.static NetworkBuffer.Type<BitSet> FixedBitSet(int length) Creates a type for a bit set of exactlylengthbits, stored in(length + 7) / 8bytes.static NetworkBuffer.Type<byte[]> FixedRawBytes(int length) Creates a type for exactlylengthbytes, unlikeRAW_BYTESwhich reads every byte left in the buffer.static NetworkBuffer.Type<double[]> FixedRawDoubles(int length) Creates a type for exactlylengthdoubles, unlikeRAW_DOUBLESwhich reads every double left in the buffer.static NetworkBuffer.Type<float[]> FixedRawFloats(int length) Creates a type for exactlylengthfloats, unlikeRAW_FLOATSwhich reads every float left in the buffer.static NetworkBuffer.Type<int[]> FixedRawInts(int length) Creates a type for exactlylengthints, unlikeRAW_INTSwhich reads every int left in the buffer.static NetworkBuffer.Type<long[]> FixedRawLongs(int length) Creates a type for exactlylengthlongs, unlikeRAW_LONGSwhich reads every long left in the buffer.static NetworkBuffer.Type<short[]> FixedRawShorts(int length) Creates a type for exactlylengthshorts, unlikeRAW_SHORTSwhich reads every short left in the buffer.index(long readIndex, long writeIndex) Sets both the read index and the write index.booleanReturns whether this buffer rejects writes, as the views created byreadOnly()do.static <T extends @UnknownNullability Object>
NetworkBuffer.Type<T> Lazy(Supplier<NetworkBuffer.Type<T>> supplier) Creates a type that gets its implementation fromsupplieron first use.static byte[]makeArray(Consumer<? super NetworkBuffer> writing) Runswritingon a new resizable buffer without registries and returns the bytes it wrote.static byte[]makeArray(Consumer<? super NetworkBuffer> writing, @Nullable Registries registries) Runswritingon a new resizable buffer and returns the bytes it wrote, in an array of exactly that length.static <T extends @UnknownNullability Object>
byte[]makeArray(NetworkBuffer.Type<T> type, T value) Encodesvaluewithtypewithout registries and returns the bytes.static <T extends @UnknownNullability Object>
byte[]makeArray(NetworkBuffer.Type<T> type, T value, @Nullable Registries registries) Encodesvaluewithtypeand returns the bytes, in an array of exactly that length.<T extends @UnknownNullability Object>
Tread(NetworkBuffer.Type<T> type) Reads a value at thereadIndex()and advances it past the value.longReturns the number of bytes between the read index and the write index,writeIndex() - readIndex().<T extends @UnknownNullability Object>
TreadAt(long index, NetworkBuffer.Type<T> type) Reads a value atindex, leaving thereadIndex()unchanged.intreadChannel(ReadableByteChannel channel) longReturns the index of the next byte to read.readIndex(long readIndex) Sets the read index.readOnly()Creates a read-only view of this buffer with the same indexes and registries, and no resize strategy.static <T extends @UnknownNullability Object>
NetworkBuffer.Type<T> Recursive(Function<? super NetworkBuffer.Type<T>, ? extends NetworkBuffer.Type<T>> func) Creates a type that refers to itself, such as a node that contains other nodes.Returns the registries for types that need them, given when the buffer was created or set withregistries(Registries).voidregistries(@Nullable Registries registries) Sets the registries for types that need them, replacing the ones given when the buffer was created.static NetworkBufferCreates a buffer with an initial capacity of 256 bytes that grows withNetworkBuffer.AutoResize.DOUBLE, and has no registries.static NetworkBufferresizableBuffer(long initialSize) Creates a buffer with an initial capacity ofinitialSizebytes that grows withNetworkBuffer.AutoResize.DOUBLE, and has no registries.static NetworkBufferresizableBuffer(long initialSize, Registries registries) Creates a buffer with an initial capacity ofinitialSizebytes that grows withNetworkBuffer.AutoResize.DOUBLE.static NetworkBufferresizableBuffer(Registries registries) Creates a buffer with an initial capacity of 256 bytes that grows withNetworkBuffer.AutoResize.DOUBLE.voidresize(long newSize) Moves the contents of this buffer into new memory ofnewSizebytes, keeping the indexes.slice(long offset, long byteLength, long readIndex, long writeIndex) A slice is an operation where the backing memory is used for the new buffer.static NetworkBufferstaticBuffer(long size) Creates a buffer with a capacity ofsizebytes, no resize strategy, and no registries.static NetworkBufferstaticBuffer(long size, Registries registries) Creates a buffer with a capacity ofsizebytes and no resize strategy, so writes past the capacity throwIndexOutOfBoundsException.static <T extends @UnknownNullability Object, D>
NetworkBuffer.Type<T> Tagged(NetworkBuffer.Type<D> discriminator, Function<? super T, ? extends D> discriminatorFromValue, Map<? super D, ? extends NetworkBuffer.Type<? extends T>> serializerMap) Creates a tagged type with no fallback, so reading and writing throwUnsupportedOperationExceptionfor a discriminator missing fromserializerMap.static <T extends @UnknownNullability Object, D>
NetworkBuffer.Type<T> Tagged(NetworkBuffer.Type<D> discriminator, Function<? super T, ? extends D> discriminatorFromValue, Map<? super D, ? extends NetworkBuffer.Type<? extends T>> serializerMap, @Nullable NetworkBuffer.Type<? extends T> fallback) Creates a type for the subtypes ofT, encoded as the discriminator of each value followed by the value in the serializer mapped to that discriminator.static <T extends @UnknownNullability Object>
NetworkBuffer.Type<T> static NetworkBufferwrap(byte[] bytes, int readIndex, int writeIndex) Creates a buffer that reads and writesbytesdirectly, with no resize strategy and no registries.static NetworkBufferwrap(byte[] bytes, int readIndex, int writeIndex, @Nullable Registries registries) Creates a buffer that reads and writesbytesdirectly, with no resize strategy.static NetworkBufferwrap(MemorySegment segment, long readIndex, long writeIndex) Creates a buffer that reads and writessegmentdirectly, with no resize strategy and no registries.static NetworkBufferwrap(MemorySegment segment, long readIndex, long writeIndex, @Nullable Registries registries) Creates a buffer that reads and writessegmentdirectly, with no resize strategy.longReturns the number of bytes between the write index and the capacity,capacity() - writeIndex().<T extends @UnknownNullability Object>
voidwrite(NetworkBuffer.Type<T> type, T value) Writes a value at thewriteIndex()and advances it past the value.<T extends @UnknownNullability Object>
voidwriteAt(long index, NetworkBuffer.Type<T> type, T value) Writes a value atindex, leaving thewriteIndex()unchanged.booleanwriteChannel(WritableByteChannel channel) Writes thereadableBytes()of this buffer tochanneland advances thereadIndex()by the number of bytes written.longReturns the index of the next byte to write.writeIndex(long writeIndex) Sets the write index.
-
Field Details
-
UNIT
-
BOOLEAN
-
BYTE
-
UNSIGNED_BYTE
-
SHORT
-
UNSIGNED_SHORT
-
INT
-
UNSIGNED_INT
-
LONG
-
FLOAT
-
DOUBLE
-
VAR_INT
-
OPTIONAL_VAR_INT
-
VAR_INT_3
-
VAR_LONG
-
RAW_BYTES
-
RAW_SHORTS
-
RAW_INTS
-
RAW_LONGS
-
RAW_FLOATS
-
RAW_DOUBLES
-
STRING
-
KEY
-
STRING_TERMINATED
-
STRING_IO_UTF8
-
NBT
-
NBT_COMPOUND
-
UNTRUSTED_NBT
-
UNTRUSTED_NBT_COMPOUND
-
BLOCK_POSITION
-
COMPONENT
-
JSON_COMPONENT
-
UUID
-
POS
-
BYTE_ARRAY
-
LONG_ARRAY
-
VAR_INT_ARRAY
-
VAR_LONG_ARRAY
-
BITSET
-
INSTANT_MS
-
PUBLIC_KEY
-
VECTOR3
-
VECTOR3D
-
VECTOR3I
-
VECTOR3B
-
LP_VECTOR3
-
QUATERNION
-
OPT_CHAT
-
OPT_BLOCK_POSITION
-
DIRECTION
-
POSE
-
-
Method Details
-
Enum
Creates a type for the constants of an enum, encoded as aVAR_INTof the ordinal. Reading an ordinal with no matching constant throwsIndexOutOfBoundsException.- Type Parameters:
E- the enum type- Parameters:
enumClass- the enum class- Returns:
- the enum type
-
EnumSet
Creates a type for a set of enum constants, encoded as aFixedBitSet(int)with one bit per constant in ordinal order.- Type Parameters:
E- the enum type- Parameters:
enumClass- the enum class- Returns:
- the enum set type
-
FixedBitSet
Creates a type for a bit set of exactlylengthbits, stored in(length + 7) / 8bytes.- Parameters:
length- the bit count, which must not be negative- Returns:
- the fixed length bit set type
-
FixedRawBytes
Creates a type for exactlylengthbytes, unlikeRAW_BYTESwhich reads every byte left in the buffer.- Parameters:
length- the element count, which must not be negative- Returns:
- the fixed length byte type
-
FixedRawShorts
Creates a type for exactlylengthshorts, unlikeRAW_SHORTSwhich reads every short left in the buffer.- Parameters:
length- the element count, which must not be negative- Returns:
- the fixed length short type
-
FixedRawInts
Creates a type for exactlylengthints, unlikeRAW_INTSwhich reads every int left in the buffer.- Parameters:
length- the element count, which must not be negative- Returns:
- the fixed length int type
-
FixedRawLongs
Creates a type for exactlylengthlongs, unlikeRAW_LONGSwhich reads every long left in the buffer.- Parameters:
length- the element count, which must not be negative- Returns:
- the fixed length long type
-
FixedRawFloats
Creates a type for exactlylengthfloats, unlikeRAW_FLOATSwhich reads every float left in the buffer.- Parameters:
length- the element count, which must not be negative- Returns:
- the fixed length float type
-
FixedRawDoubles
Creates a type for exactlylengthdoubles, unlikeRAW_DOUBLESwhich reads every double left in the buffer.- Parameters:
length- the element count, which must not be negative- Returns:
- the fixed length double type
-
Lazy
static <T extends @UnknownNullability Object> NetworkBuffer.Type<T> Lazy(Supplier<NetworkBuffer.Type<T>> supplier) Creates a type that gets its implementation fromsupplieron first use. The supplier should be thread safe, because first uses from several threads at once can each call it.- Type Parameters:
T- the value type- Parameters:
supplier- the supplier of the type- Returns:
- the lazy type
-
TypedNBT
Creates a type that encodes values withserializerasNBT, and reads them withUNTRUSTED_NBT. Reading and writing throwIllegalStateExceptionwhen the buffer has noregistries(), andIllegalArgumentExceptionwhen the codec fails.- Type Parameters:
T- the value type- Parameters:
serializer- the codec for the values- Returns:
- the NBT type
-
Either
static <L,R> NetworkBuffer.Type<Either<L,R>> Either(NetworkBuffer.Type<L> left, NetworkBuffer.Type<R> right) Creates a type for anEither, encoded as aBOOLEANthat istruefor a left value, followed by the value.- Type Parameters:
L- the left typeR- the right type- Parameters:
left- the type of left valuesright- the type of right values- Returns:
- the either type
-
Recursive
static <T extends @UnknownNullability Object> NetworkBuffer.Type<T> Recursive(Function<? super NetworkBuffer.Type<T>, ? extends NetworkBuffer.Type<T>> func) Creates a type that refers to itself, such as a node that contains other nodes.funcis called once, right away, with a type that delegates to the type it returns. That reference must not read or write beforefuncreturns.- Type Parameters:
T- the value type- Parameters:
func- the function that builds the type from a reference to itself- Returns:
- the type returned by
func
-
Tagged
static <T extends @UnknownNullability Object, D> NetworkBuffer.Type<T> Tagged(NetworkBuffer.Type<D> discriminator, Function<? super T, ? extends D> discriminatorFromValue, Map<? super D, ? extends NetworkBuffer.Type<? extends T>> serializerMap, @Nullable @Nullable NetworkBuffer.Type<? extends T> fallback) Creates a type for the subtypes ofT, encoded as the discriminator of each value followed by the value in the serializer mapped to that discriminator. The fallback serializer handles discriminators missing fromserializerMap. Without a fallback, reading and writing throwUnsupportedOperationExceptionfor a missing discriminator.- Type Parameters:
T- the value typeD- the discriminator type- Parameters:
discriminator- the type of the discriminatordiscriminatorFromValue- the discriminator of a valueserializerMap- the serializer for each discriminator, which this method copiesfallback- the serializer for other discriminators, ornullfor none- Returns:
- the tagged type
- Throws:
NullPointerException- ifserializerMapcontains a null key or value
-
Tagged
static <T extends @UnknownNullability Object, D> NetworkBuffer.Type<T> Tagged(NetworkBuffer.Type<D> discriminator, Function<? super T, ? extends D> discriminatorFromValue, Map<? super D, ? extends NetworkBuffer.Type<? extends T>> serializerMap) Creates a tagged type with no fallback, so reading and writing throwUnsupportedOperationExceptionfor a discriminator missing fromserializerMap.- Type Parameters:
T- the value typeD- the discriminator type- Parameters:
discriminator- the type of the discriminatordiscriminatorFromValue- the discriminator of a valueserializerMap- the serializer for each discriminator, which this method copies- Returns:
- the tagged type
- Throws:
NullPointerException- ifserializerMapcontains a null key or value- See Also:
-
write
<T extends @UnknownNullability Object> void write(NetworkBuffer.Type<T> type, T value) throws IndexOutOfBoundsException Writes a value at thewriteIndex()and advances it past the value. The buffer is resized first when it needs more room and has a resize strategy.- Type Parameters:
T- the value type- Parameters:
type- the type of the valuevalue- the value to write- Throws:
IndexOutOfBoundsException- if the value does not fit and the buffer cannot growIllegalArgumentException- if this buffer is read-only
-
read
<T extends @UnknownNullability Object> T read(NetworkBuffer.Type<T> type) throws IndexOutOfBoundsException Reads a value at thereadIndex()and advances it past the value.- Type Parameters:
T- the value type- Parameters:
type- the type of the value- Returns:
- the value
- Throws:
IndexOutOfBoundsException- if the value extends past thecapacity()IllegalArgumentException- if this buffer is a dummy
-
writeAt
<T extends @UnknownNullability Object> void writeAt(long index, NetworkBuffer.Type<T> type, T value) throws IndexOutOfBoundsException Writes a value atindex, leaving thewriteIndex()unchanged.- Type Parameters:
T- the value type- Parameters:
index- the index to write attype- the type of the valuevalue- the value to write- Throws:
IndexOutOfBoundsException- if the value does not fit and the buffer cannot growIllegalArgumentException- if this buffer is read-only
-
readAt
<T extends @UnknownNullability Object> T readAt(long index, NetworkBuffer.Type<T> type) throws IndexOutOfBoundsException Reads a value atindex, leaving thereadIndex()unchanged.- Type Parameters:
T- the value type- Parameters:
index- the index to read attype- the type of the value- Returns:
- the value
- Throws:
IndexOutOfBoundsException- if the value extends past thecapacity()IllegalArgumentException- if this buffer is a dummy
-
copyTo
void copyTo(long srcOffset, byte[] dest, int destOffset, int length) Copieslengthbytes starting atsrcOffsetintodest, ignoring the read and write indexes.- Parameters:
srcOffset- the index of the first byte to copydest- the destination arraydestOffset- the index indestto copy tolength- the number of bytes to copy- Throws:
IndexOutOfBoundsException- if either range is out of boundsIllegalArgumentException- if this buffer is a dummy
-
copyTo
Copieslengthbytes starting atsrcOffsetintodest, ignoring the read and write indexes.- Parameters:
srcOffset- the index of the first byte to copydest- the destination segmentdestOffset- the index indestto copy tolength- the number of bytes to copy- Throws:
IndexOutOfBoundsException- if either range is out of boundsIllegalArgumentException- if this buffer is a dummy, ordestis read-only
-
extractBytes
Runsextractoron this buffer and returns a copy of the bytes it read, from thereadIndex()before the call to the one after it.- Parameters:
extractor- the reads to capture- Returns:
- the bytes read by
extractor - Throws:
IllegalArgumentException- if this buffer is a dummy
-
clear
NetworkBuffer clear()Sets the read and write indexes to 0. The stored bytes are not zeroed.- Returns:
- this buffer
-
writeIndex
long writeIndex()Returns the index of the next byte to write.- Returns:
- the write index
-
readIndex
long readIndex()Returns the index of the next byte to read.- Returns:
- the read index
-
writeIndex
Sets the write index. The index is not validated.- Parameters:
writeIndex- the new write index- Returns:
- this buffer
-
readIndex
Sets the read index. The index is not validated.- Parameters:
readIndex- the new read index- Returns:
- this buffer
-
index
Sets both the read index and the write index. The indexes are not validated.- Parameters:
readIndex- the new read indexwriteIndex- the new write index- Returns:
- this buffer
-
advanceWrite
long advanceWrite(long length) Moves the write index forward bylength.- Parameters:
length- the number of bytes to advance- Returns:
- the previous write index
-
advanceRead
long advanceRead(long length) Moves the read index forward bylength.- Parameters:
length- the number of bytes to advance- Returns:
- the previous read index
-
readableBytes
long readableBytes()Returns the number of bytes between the read index and the write index,writeIndex() - readIndex().- Returns:
- the readable bytes
-
writableBytes
long writableBytes()Returns the number of bytes between the write index and the capacity,capacity() - writeIndex(). A buffer with a resize strategy can grow past this.- Returns:
- the writable bytes
-
capacity
long capacity()Returns the size of the memory backing this buffer. A dummy buffer reportsLong.MAX_VALUE.- Returns:
- the capacity
-
readOnly
Creates a read-only view of this buffer with the same indexes and registries, and no resize strategy. The view shares memory with this buffer until this buffer is resized, after which it keeps the old bytes.- Returns:
- the read-only view
- Throws:
IllegalArgumentException- if this buffer is a dummy
-
isReadOnly
boolean isReadOnly()Returns whether this buffer rejects writes, as the views created byreadOnly()do.- Returns:
- true if this buffer is read-only
-
resize
void resize(long newSize) Moves the contents of this buffer into new memory ofnewSizebytes, keeping the indexes. Buffers without a resize strategy can be resized this way too. Views created byreadOnly()orslice(long, long, long, long)keep the old memory.- Parameters:
newSize- the new capacity, which must be greater than the current capacity- Throws:
IllegalArgumentException- ifnewSizeis not greater than the current capacityIllegalArgumentException- if this buffer is read-only or a dummy
-
ensureWritable
Ensures that at leastlengthbytes can be written at thewriteIndex(), resizing the buffer with its resize strategy when needed.- Parameters:
length- the number of bytes, which must not be negative- Throws:
IllegalArgumentException- iflengthis negative, or this buffer is read-onlyIndexOutOfBoundsException- if the buffer is too small and has no resize strategy, or the strategy returns the current capacity
-
ensureReadable
Ensures that at leastlengthbytes are readable, as counted byreadableBytes().- Parameters:
length- the number of bytes, which must not be negative- Throws:
IllegalArgumentException- iflengthis negativeIndexOutOfBoundsException- if fewer thanlengthbytes are readable
-
compact
void compact()Moves the readable bytes to the start of the buffer and lowers both indexes by the old read index. The capacity does not change.- Throws:
IllegalArgumentException- if this buffer is read-only or a dummy
-
copy
Copieslengthbytes starting atindexinto a new buffer with the given indexes. The copy keeps the resize strategy and registries of this buffer.- Parameters:
index- the index of the first byte to copylength- the number of bytes to copy, which becomes the capacity of the copyreadIndex- the read index of the copywriteIndex- the write index of the copy- Returns:
- the new buffer
- Throws:
IndexOutOfBoundsException- if the range is outside the capacityIllegalArgumentException- if this buffer is a dummy
-
copy
Copieslengthbytes starting atindexinto a new buffer with the current indexes of this buffer.- Parameters:
index- the index of the first byte to copylength- the number of bytes to copy, which becomes the capacity of the copy- Returns:
- the new buffer
- Throws:
IndexOutOfBoundsException- if the range is outside the capacityIllegalArgumentException- if this buffer is a dummy- See Also:
-
readChannel
Reads fromchannelinto thewritableBytes()of this buffer and advances thewriteIndex(). The buffer is not resized.- Parameters:
channel- the channel to read from- Returns:
- the number of bytes read
- Throws:
IOException- if the channel fails or has reached the end of its streamIllegalArgumentException- if this buffer is a dummy
-
writeChannel
Writes thereadableBytes()of this buffer tochanneland advances thereadIndex()by the number of bytes written.- Parameters:
channel- the channel to write to- Returns:
- true if every readable byte was written
- Throws:
IOException- if the channel failsIllegalArgumentException- if this buffer is a dummy
-
cipher
Encrypts or decryptslengthbytes starting atstartin place withcipher.- Parameters:
cipher- the cipher to update with the bytesstart- the index of the first bytelength- the number of bytes- Throws:
IllegalArgumentException- if this buffer is a dummy
-
compress
Compresseslengthbytes starting atstartwith aDeflaterintooutputat its write index, and advances the write index ofoutput. The output is not resized, so it needs enough writable bytes for the compressed data.- Parameters:
start- the index of the first bytelength- the number of bytesoutput- the buffer to write the compressed bytes to- Returns:
- the number of compressed bytes written
- Throws:
IllegalArgumentException- if either buffer is a dummy, oroutputis read-only
-
decompress
Decompresseslengthbytes starting atstartwith anInflaterintooutputat its write index, and advances the write index ofoutput. The output is not resized.- Parameters:
start- the index of the first bytelength- the number of bytesoutput- the buffer to write the decompressed bytes to- Returns:
- the number of decompressed bytes written
- Throws:
DataFormatException- if the data is invalid or incomplete, or does not fit in the writable bytes ofoutputIllegalArgumentException- if either buffer is a dummy, oroutputis read-only
-
registries
Returns the registries for types that need them, given when the buffer was created or set withregistries(Registries).- Returns:
- the registries, or
nullif there are none
-
registries
Sets the registries for types that need them, replacing the ones given when the buffer was created. Buffers already created from this one byreadOnly(),slice(long, long, long, long), orcopy(long, long, long, long)keep their own registries.- Parameters:
registries- the registries, ornullfor none
-
slice
@Contract(pure=true, value="_, _, _, _ -> new") NetworkBuffer slice(long offset, long byteLength, long readIndex, long writeIndex) A slice is an operation where the backing memory is used for the new buffer. Consider it a view over the backing memory region.- Parameters:
offset- the position to start the slicebyteLength- the length of the slice, equal tocapacity()readIndex- the read indexwriteIndex- the write index- Returns:
- a new buffer
- Throws:
IllegalArgumentException- if this buffer is a dummy- API Note:
- With resized segments, you could observe behavior where you may see stale data or close arenas.
To avoid this, do not use resizable segments in a way where they are written or resized like
resize(long). - Implementation Note:
registries()are copied into the new buffer
-
builder
Creates a builder for a buffer with an initial capacity ofsizebytes. The buffer has no resize strategy and no registries unless the builder sets them.- Parameters:
size- the initial capacity, which must not be negative- Returns:
- the new builder
-
staticBuffer
Creates a buffer with a capacity ofsizebytes and no resize strategy, so writes past the capacity throwIndexOutOfBoundsException.- Parameters:
size- the capacityregistries- the registries for types that need them- Returns:
- the new buffer
-
staticBuffer
Creates a buffer with a capacity ofsizebytes, no resize strategy, and no registries.- Parameters:
size- the capacity- Returns:
- the new buffer
- See Also:
-
resizableBuffer
Creates a buffer with an initial capacity ofinitialSizebytes that grows withNetworkBuffer.AutoResize.DOUBLE.- Parameters:
initialSize- the initial capacityregistries- the registries for types that need them- Returns:
- the new buffer
-
resizableBuffer
Creates a buffer with an initial capacity ofinitialSizebytes that grows withNetworkBuffer.AutoResize.DOUBLE, and has no registries.- Parameters:
initialSize- the initial capacity- Returns:
- the new buffer
-
resizableBuffer
Creates a buffer with an initial capacity of 256 bytes that grows withNetworkBuffer.AutoResize.DOUBLE.- Parameters:
registries- the registries for types that need them- Returns:
- the new buffer
-
resizableBuffer
Creates a buffer with an initial capacity of 256 bytes that grows withNetworkBuffer.AutoResize.DOUBLE, and has no registries.- Returns:
- the new buffer
-
wrap
static NetworkBuffer wrap(MemorySegment segment, long readIndex, long writeIndex, @Nullable @Nullable Registries registries) Creates a buffer that reads and writessegmentdirectly, with no resize strategy. Useful when you already have a memory segment.- Parameters:
segment- the memory to usereadIndex- thereadIndex()writeIndex- thewriteIndex()registries- theregistries(), ornull- Returns:
- the new buffer
-
wrap
Creates a buffer that reads and writessegmentdirectly, with no resize strategy and no registries.- Parameters:
segment- the memory to usereadIndex- thereadIndex()writeIndex- thewriteIndex()- Returns:
- the new buffer
- See Also:
-
wrap
static NetworkBuffer wrap(byte[] bytes, int readIndex, int writeIndex, @Nullable @Nullable Registries registries) Creates a buffer that reads and writesbytesdirectly, with no resize strategy. Useful when you already have abyte[].- Parameters:
bytes- the array to usereadIndex- thereadIndex()writeIndex- thewriteIndex()registries- theregistries(), ornull- Returns:
- the new buffer
-
wrap
Creates a buffer that reads and writesbytesdirectly, with no resize strategy and no registries.- Parameters:
bytes- the array to usereadIndex- thereadIndex()writeIndex- thewriteIndex()- Returns:
- the new buffer
- See Also:
-
makeArray
static byte[] makeArray(Consumer<? super NetworkBuffer> writing, @Nullable @Nullable Registries registries) Runswritingon a new resizable buffer and returns the bytes it wrote, in an array of exactly that length.- Parameters:
writing- the writes to captureregistries- the registries for types that need them, ornull- Returns:
- the written bytes
-
makeArray
Runswritingon a new resizable buffer without registries and returns the bytes it wrote.- Parameters:
writing- the writes to capture- Returns:
- the written bytes
- See Also:
-
makeArray
static <T extends @UnknownNullability Object> byte[] makeArray(NetworkBuffer.Type<T> type, T value, @Nullable @Nullable Registries registries) Encodesvaluewithtypeand returns the bytes, in an array of exactly that length.- Type Parameters:
T- the value type- Parameters:
type- the type of the valuevalue- the value to encoderegistries- the registries for types that need them, ornull- Returns:
- the encoded bytes
-
makeArray
Encodesvaluewithtypewithout registries and returns the bytes.- Type Parameters:
T- the value type- Parameters:
type- the type of the valuevalue- the value to encode- Returns:
- the encoded bytes
- See Also:
-
copy
static void copy(NetworkBuffer srcBuffer, long srcOffset, NetworkBuffer dstBuffer, long dstOffset, long length) Copieslengthbytes fromsrcBufferatsrcOffsettodstBufferatdstOffset, ignoring the read and write indexes of both buffers.dstBufferis not resized.- Parameters:
srcBuffer- the buffer to copy fromsrcOffset- the index of the first byte to copydstBuffer- the buffer to copy todstOffset- the index indstBufferto copy tolength- the number of bytes to copy- Throws:
IndexOutOfBoundsException- if either range is outside the capacity of its bufferIllegalArgumentException- if either buffer is a dummy, ordstBufferis read-only
-
equals
Checks whether two buffers have the same capacity and the same bytes across it, ignoring their read and write indexes.- Parameters:
buffer1- the first bufferbuffer2- the second buffer- Returns:
- true if the contents are equal
- Throws:
IllegalArgumentException- if either buffer is a dummy
-