Rename Buf to Buffer and Allocator to BufferAllocator

This commit is contained in:
Chris Vest 2021-02-12 18:22:07 +01:00
parent 5f1f0bae38
commit eef97dd1fd
30 changed files with 1579 additions and 1567 deletions

View File

@ -17,7 +17,7 @@ package io.netty.buffer.api;
/** /**
* Methods for accessing and controlling the internals of an allocator. * Methods for accessing and controlling the internals of an allocator.
* This interface is intended to be used by implementors of the {@link Allocator}, {@link Buf} and * This interface is intended to be used by implementors of the {@link BufferAllocator}, {@link Buffer} and
* {@link MemoryManager} interfaces. * {@link MemoryManager} interfaces.
*/ */
public interface AllocatorControl { public interface AllocatorControl {
@ -25,19 +25,19 @@ public interface AllocatorControl {
* Allocate a buffer that is not tethered to any particular {@link Drop} implementation, * Allocate a buffer that is not tethered to any particular {@link Drop} implementation,
* and return the recoverable memory object from it. * and return the recoverable memory object from it.
* <p> * <p>
* This allows a buffer to implement {@link Buf#ensureWritable(int)} by having new memory allocated to it, * This allows a buffer to implement {@link Buffer#ensureWritable(int)} by having new memory allocated to it,
* without that memory being attached to some other lifetime. * without that memory being attached to some other lifetime.
* *
* @param originator The buffer that originated the request for an untethered memory allocated. * @param originator The buffer that originated the request for an untethered memory allocated.
* @param size The size of the requested memory allocation, in bytes. * @param size The size of the requested memory allocation, in bytes.
* @return A "recoverable memory" object that is the requested allocation. * @return A "recoverable memory" object that is the requested allocation.
*/ */
Object allocateUntethered(Buf originator, int size); Object allocateUntethered(Buffer originator, int size);
/** /**
* Return memory to the allocator, after it has been untethered from it's lifetime. * Return memory to the allocator, after it has been untethered from it's lifetime.
* This either happens if the memory has leaked and been re-captured, or if it is no longer in use by a buffer * This either happens if the memory has leaked and been re-captured, or if it is no longer in use by a buffer
* through {@link Buf#ensureWritable(int)}. * through {@link Buffer#ensureWritable(int)}.
* *
* @param memory The untethered memory to return to the allocator. * @param memory The untethered memory to return to the allocator.
*/ */

View File

@ -30,8 +30,9 @@ import java.nio.ByteOrder;
* *
* <h3>Creating a buffer</h3> * <h3>Creating a buffer</h3>
* *
* Buffers are created by {@linkplain Allocator allocators}, and their {@code allocate} family of methods. * Buffers are created by {@linkplain BufferAllocator allocators}, and their {@code allocate} family of methods.
* A number of standard allocators exist, and ara available through static methods on the {@code Allocator} interface. * A number of standard allocators exist, and ara available through static methods on the {@code BufferAllocator}
* interface.
* *
* <h3>Life cycle and reference counting</h3> * <h3>Life cycle and reference counting</h3>
* *
@ -70,7 +71,7 @@ import java.nio.ByteOrder;
* To send a buffer to another thread, the buffer must not have any outstanding borrows. * To send a buffer to another thread, the buffer must not have any outstanding borrows.
* That is to say, all {@linkplain #acquire() acquires} must have been paired with a {@link #close()}; * That is to say, all {@linkplain #acquire() acquires} must have been paired with a {@link #close()};
* all {@linkplain #slice() slices} must have been closed. * all {@linkplain #slice() slices} must have been closed.
* And if this buffer is a constituent of a {@linkplain Allocator#compose(Deref...) composite buffer}, * And if this buffer is a constituent of a {@linkplain BufferAllocator#compose(Deref...) composite buffer},
* then that composite buffer must be closed. * then that composite buffer must be closed.
* And if this buffer is itself a composite buffer, then it must own all of its constituent buffers. * And if this buffer is itself a composite buffer, then it must own all of its constituent buffers.
* The {@link #isOwned()} method can be used on any buffer to check if it can be sent or not. * The {@link #isOwned()} method can be used on any buffer to check if it can be sent or not.
@ -106,14 +107,14 @@ import java.nio.ByteOrder;
* </pre> * </pre>
* *
*/ */
public interface Buf extends Rc<Buf>, BufAccessors { public interface Buffer extends Rc<Buffer>, BufferAccessors {
/** /**
* Change the default byte order of this buffer, and return this buffer. * Change the default byte order of this buffer, and return this buffer.
* *
* @param order The new default byte order, used by accessor methods that don't use an explicit byte order. * @param order The new default byte order, used by accessor methods that don't use an explicit byte order.
* @return This buffer instance. * @return This buffer instance.
*/ */
Buf order(ByteOrder order); Buffer order(ByteOrder order);
/** /**
* The default byte order of this buffer. * The default byte order of this buffer.
@ -139,11 +140,11 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* Set the reader offset. Make the next read happen from the given offset into the buffer. * Set the reader offset. Make the next read happen from the given offset into the buffer.
* *
* @param offset The reader offset to set. * @param offset The reader offset to set.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the specified {@code offset} is less than zero or greater than the current * @throws IndexOutOfBoundsException if the specified {@code offset} is less than zero or greater than the current
* {@link #writerOffset()}. * {@link #writerOffset()}.
*/ */
Buf readerOffset(int offset); Buffer readerOffset(int offset);
/** /**
* Get the current writer offset. The next write will happen at this byte offset into the byffer. * Get the current writer offset. The next write will happen at this byte offset into the byffer.
@ -156,12 +157,12 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* Set the writer offset. Make the next write happen at the given offset. * Set the writer offset. Make the next write happen at the given offset.
* *
* @param offset The writer offset to set. * @param offset The writer offset to set.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the specified {@code offset} is less than the current * @throws IndexOutOfBoundsException if the specified {@code offset} is less than the current
* {@link #readerOffset()} or greater than {@link #capacity()}. * {@link #readerOffset()} or greater than {@link #capacity()}.
* @throws IllegalStateException if this buffer is {@linkplain #readOnly() read-only}. * @throws IllegalStateException if this buffer is {@linkplain #readOnly() read-only}.
*/ */
Buf writerOffset(int offset); Buffer writerOffset(int offset);
/** /**
* Returns the number of readable bytes which is equal to {@code (writerOffset() - readerOffset())}. * Returns the number of readable bytes which is equal to {@code (writerOffset() - readerOffset())}.
@ -183,10 +184,10 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* #writerOffset()} are not modified. * #writerOffset()} are not modified.
* *
* @param value The byte value to write at every position in the buffer. * @param value The byte value to write at every position in the buffer.
* @return This Buf. * @return This Buffer.
* @throws IllegalStateException if this buffer is {@linkplain #readOnly() read-only}. * @throws IllegalStateException if this buffer is {@linkplain #readOnly() read-only}.
*/ */
Buf fill(byte value); Buffer fill(byte value);
/** /**
* Give the native memory address backing this buffer, or return 0 if this buffer has no native memory address. * Give the native memory address backing this buffer, or return 0 if this buffer has no native memory address.
@ -199,7 +200,7 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* *
* @return this buffer. * @return this buffer.
*/ */
Buf readOnly(boolean readOnly); Buffer readOnly(boolean readOnly);
/** /**
* Query if this buffer is read-only or not. * Query if this buffer is read-only or not.
@ -224,7 +225,7 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* @return A new buffer instance, with independent {@link #readerOffset()} and {@link #writerOffset()}, * @return A new buffer instance, with independent {@link #readerOffset()} and {@link #writerOffset()},
* that is a view of the readable region of this buffer. * that is a view of the readable region of this buffer.
*/ */
default Buf slice() { default Buffer slice() {
return slice(readerOffset(), readableBytes()); return slice(readerOffset(), readableBytes());
} }
@ -243,7 +244,7 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* @return A new buffer instance, with independent {@link #readerOffset()} and {@link #writerOffset()}, * @return A new buffer instance, with independent {@link #readerOffset()} and {@link #writerOffset()},
* that is a view of the given region of this buffer. * that is a view of the given region of this buffer.
*/ */
Buf slice(int offset, int length); Buffer slice(int offset, int length);
/** /**
* Copies the given length of data from this buffer into the given destination array, beginning at the given source * Copies the given length of data from this buffer into the given destination array, beginning at the given source
@ -303,13 +304,13 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* @throws IndexOutOfBoundsException if the source or destination positions, or the length, are negative, * @throws IndexOutOfBoundsException if the source or destination positions, or the length, are negative,
* or if the resulting end positions reaches beyond the end of either this buffer or the destination array. * or if the resulting end positions reaches beyond the end of either this buffer or the destination array.
*/ */
void copyInto(int srcPos, Buf dest, int destPos, int length); void copyInto(int srcPos, Buffer dest, int destPos, int length);
/** /**
* Resets the {@linkplain #readerOffset() read offset} and the {@linkplain #writerOffset() write offset} on this * Resets the {@linkplain #readerOffset() read offset} and the {@linkplain #writerOffset() write offset} on this
* buffer to their initial values. * buffer to their initial values.
*/ */
default Buf reset() { default Buffer reset() {
readerOffset(0); readerOffset(0);
writerOffset(0); writerOffset(0);
return this; return this;
@ -386,8 +387,8 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* bytes. * bytes.
* The buffer must be in {@linkplain #isOwned() an owned state}, or an exception will be thrown. * The buffer must be in {@linkplain #isOwned() an owned state}, or an exception will be thrown.
* If this buffer already has the necessary space, then this method returns immediately. * If this buffer already has the necessary space, then this method returns immediately.
* If this buffer does not already have the necessary space, then it will be expanded using the {@link Allocator} * If this buffer does not already have the necessary space, then it will be expanded using the
* the buffer was created with. * {@link BufferAllocator} the buffer was created with.
* This method is the same as calling {@link #ensureWritable(int, boolean)} where {@code allowCompaction} is * This method is the same as calling {@link #ensureWritable(int, boolean)} where {@code allowCompaction} is
* {@code false}. * {@code false}.
* *
@ -418,8 +419,8 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* </li> * </li>
* <li> * <li>
* Regardless of the value of the {@code allowCompaction}, the implementation may make more space available * Regardless of the value of the {@code allowCompaction}, the implementation may make more space available
* by just allocating more or larger buffers. This allocation would use the same {@link Allocator} that this * by just allocating more or larger buffers. This allocation would use the same {@link BufferAllocator}
* buffer was created with. * that this buffer was created with.
* </li> * </li>
* <li> * <li>
* If {@code allowCompaction} is {@code true}, then the implementation may choose to do a combination of * If {@code allowCompaction} is {@code true}, then the implementation may choose to do a combination of
@ -480,7 +481,7 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* *
* @return A new buffer with independent and exclusive ownership over the read and readable bytes from this buffer. * @return A new buffer with independent and exclusive ownership over the read and readable bytes from this buffer.
*/ */
Buf bifurcate(); Buffer bifurcate();
/** /**
* Discards the read bytes, and moves the buffer contents to the beginning of the buffer. * Discards the read bytes, and moves the buffer contents to the beginning of the buffer.

View File

@ -16,599 +16,599 @@
package io.netty.buffer.api; package io.netty.buffer.api;
/** /**
* This interface is just the primitive data accessor methods that {@link Buf} exposes. * This interface is just the primitive data accessor methods that {@link Buffer} exposes.
* It can be useful if you only need the data access methods, and perhaps wish to decorate or modify their behaviour. * It can be useful if you only need the data access methods, and perhaps wish to decorate or modify their behaviour.
* Usually, you'd use the {@link Buf} interface directly, since this lets you properly control the buffer reference * Usually, you'd use the {@link Buffer} interface directly, since this lets you properly control the buffer reference
* count. * count.
*/ */
public interface BufAccessors { public interface BufferAccessors {
// <editor-fold defaultstate="collapsed" desc="Primitive accessors interface."> // <editor-fold defaultstate="collapsed" desc="Primitive accessors interface.">
/** /**
* Get the byte value at the current {@link Buf#readerOffset()}, * Get the byte value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Byte#BYTES}. * and increases the reader offset by {@link Byte#BYTES}.
* The value is read using a two's complement 8-bit encoding, * The value is read using a two's complement 8-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The byte value at the current reader offset. * @return The byte value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Byte#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Byte#BYTES}.
*/ */
byte readByte(); byte readByte();
/** /**
* Get the byte value at the given reader offset. * Get the byte value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using a two's complement 8-bit encoding, * The value is read using a two's complement 8-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The byte value at the given offset. * @return The byte value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Byte#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Byte#BYTES}.
*/ */
byte getByte(int roff); byte getByte(int roff);
/** /**
* Get the unsigned byte value at the current {@link Buf#readerOffset()}, * Get the unsigned byte value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Byte#BYTES}. * and increases the reader offset by {@link Byte#BYTES}.
* The value is read using an unsigned two's complement 8-bit encoding, * The value is read using an unsigned two's complement 8-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The unsigned byte value at the current reader offset. * @return The unsigned byte value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Byte#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Byte#BYTES}.
*/ */
int readUnsignedByte(); int readUnsignedByte();
/** /**
* Get the unsigned byte value at the given reader offset. * Get the unsigned byte value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using an unsigned two's complement 8-bit encoding, * The value is read using an unsigned two's complement 8-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The unsigned byte value at the given offset. * @return The unsigned byte value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Byte#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Byte#BYTES}.
*/ */
int getUnsignedByte(int roff); int getUnsignedByte(int roff);
/** /**
* Set the given byte value at the current {@link Buf#writerOffset()}, * Set the given byte value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Byte#BYTES}. * and increase the writer offset by {@link Byte#BYTES}.
* The value is written using a two's complement 8-bit encoding, * The value is written using a two's complement 8-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The byte value to write. * @param value The byte value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Byte#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Byte#BYTES}.
*/ */
Buf writeByte(byte value); Buffer writeByte(byte value);
/** /**
* Set the given byte value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given byte value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using a two's complement 8-bit encoding, * The value is written using a two's complement 8-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The byte value to write. * @param value The byte value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Byte#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Byte#BYTES}.
*/ */
Buf setByte(int woff, byte value); Buffer setByte(int woff, byte value);
/** /**
* Set the given unsigned byte value at the current {@link Buf#writerOffset()}, * Set the given unsigned byte value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Byte#BYTES}. * and increase the writer offset by {@link Byte#BYTES}.
* The value is written using an unsigned two's complement 8-bit encoding, * The value is written using an unsigned two's complement 8-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Byte#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Byte#BYTES}.
*/ */
Buf writeUnsignedByte(int value); Buffer writeUnsignedByte(int value);
/** /**
* Set the given unsigned byte value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given unsigned byte value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using an unsigned two's complement 8-bit encoding, * The value is written using an unsigned two's complement 8-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Byte#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Byte#BYTES}.
*/ */
Buf setUnsignedByte(int woff, int value); Buffer setUnsignedByte(int woff, int value);
/** /**
* Get the char value at the current {@link Buf#readerOffset()}, * Get the char value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by 2. * and increases the reader offset by 2.
* The value is read using a 2-byte UTF-16 encoding, * The value is read using a 2-byte UTF-16 encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The char value at the current reader offset. * @return The char value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than 2. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than 2.
*/ */
char readChar(); char readChar();
/** /**
* Get the char value at the given reader offset. * Get the char value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using a 2-byte UTF-16 encoding, * The value is read using a 2-byte UTF-16 encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The char value at the given offset. * @return The char value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus 2. * greater than {@link Buffer#capacity()} minus 2.
*/ */
char getChar(int roff); char getChar(int roff);
/** /**
* Set the given char value at the current {@link Buf#writerOffset()}, * Set the given char value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by 2. * and increase the writer offset by 2.
* The value is written using a 2-byte UTF-16 encoding, * The value is written using a 2-byte UTF-16 encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The char value to write. * @param value The char value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than 2. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than 2.
*/ */
Buf writeChar(char value); Buffer writeChar(char value);
/** /**
* Set the given char value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given char value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using a 2-byte UTF-16 encoding, * The value is written using a 2-byte UTF-16 encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The char value to write. * @param value The char value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus 2. * greater than {@link Buffer#capacity()} minus 2.
*/ */
Buf setChar(int woff, char value); Buffer setChar(int woff, char value);
/** /**
* Get the short value at the current {@link Buf#readerOffset()}, * Get the short value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Short#BYTES}. * and increases the reader offset by {@link Short#BYTES}.
* The value is read using a two's complement 16-bit encoding, * The value is read using a two's complement 16-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The short value at the current reader offset. * @return The short value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Short#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Short#BYTES}.
*/ */
short readShort(); short readShort();
/** /**
* Get the short value at the given reader offset. * Get the short value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using a two's complement 16-bit encoding, * The value is read using a two's complement 16-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The short value at the given offset. * @return The short value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Short#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Short#BYTES}.
*/ */
short getShort(int roff); short getShort(int roff);
/** /**
* Get the unsigned short value at the current {@link Buf#readerOffset()}, * Get the unsigned short value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Short#BYTES}. * and increases the reader offset by {@link Short#BYTES}.
* The value is read using an unsigned two's complement 16-bit encoding, * The value is read using an unsigned two's complement 16-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The unsigned short value at the current reader offset. * @return The unsigned short value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Short#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Short#BYTES}.
*/ */
int readUnsignedShort(); int readUnsignedShort();
/** /**
* Get the unsigned short value at the given reader offset. * Get the unsigned short value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using an unsigned two's complement 16-bit encoding, * The value is read using an unsigned two's complement 16-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The unsigned short value at the given offset. * @return The unsigned short value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Short#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Short#BYTES}.
*/ */
int getUnsignedShort(int roff); int getUnsignedShort(int roff);
/** /**
* Set the given short value at the current {@link Buf#writerOffset()}, * Set the given short value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Short#BYTES}. * and increase the writer offset by {@link Short#BYTES}.
* The value is written using a two's complement 16-bit encoding, * The value is written using a two's complement 16-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The short value to write. * @param value The short value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Short#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Short#BYTES}.
*/ */
Buf writeShort(short value); Buffer writeShort(short value);
/** /**
* Set the given short value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given short value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using a two's complement 16-bit encoding, * The value is written using a two's complement 16-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The short value to write. * @param value The short value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Short#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Short#BYTES}.
*/ */
Buf setShort(int woff, short value); Buffer setShort(int woff, short value);
/** /**
* Set the given unsigned short value at the current {@link Buf#writerOffset()}, * Set the given unsigned short value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Short#BYTES}. * and increase the writer offset by {@link Short#BYTES}.
* The value is written using an unsigned two's complement 16-bit encoding, * The value is written using an unsigned two's complement 16-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Short#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Short#BYTES}.
*/ */
Buf writeUnsignedShort(int value); Buffer writeUnsignedShort(int value);
/** /**
* Set the given unsigned short value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given unsigned short value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using an unsigned two's complement 16-bit encoding, * The value is written using an unsigned two's complement 16-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Short#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Short#BYTES}.
*/ */
Buf setUnsignedShort(int woff, int value); Buffer setUnsignedShort(int woff, int value);
/** /**
* Get the int value at the current {@link Buf#readerOffset()}, * Get the int value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by 3. * and increases the reader offset by 3.
* The value is read using a two's complement 24-bit encoding, * The value is read using a two's complement 24-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The int value at the current reader offset. * @return The int value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than 3. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than 3.
*/ */
int readMedium(); int readMedium();
/** /**
* Get the int value at the given reader offset. * Get the int value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using a two's complement 24-bit encoding, * The value is read using a two's complement 24-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The int value at the given offset. * @return The int value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus 3. * greater than {@link Buffer#capacity()} minus 3.
*/ */
int getMedium(int roff); int getMedium(int roff);
/** /**
* Get the unsigned int value at the current {@link Buf#readerOffset()}, * Get the unsigned int value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by 3. * and increases the reader offset by 3.
* The value is read using an unsigned two's complement 24-bit encoding, * The value is read using an unsigned two's complement 24-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The unsigned int value at the current reader offset. * @return The unsigned int value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than 3. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than 3.
*/ */
int readUnsignedMedium(); int readUnsignedMedium();
/** /**
* Get the unsigned int value at the given reader offset. * Get the unsigned int value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using an unsigned two's complement 24-bit encoding, * The value is read using an unsigned two's complement 24-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The unsigned int value at the given offset. * @return The unsigned int value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus 3. * greater than {@link Buffer#capacity()} minus 3.
*/ */
int getUnsignedMedium(int roff); int getUnsignedMedium(int roff);
/** /**
* Set the given int value at the current {@link Buf#writerOffset()}, * Set the given int value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by 3. * and increase the writer offset by 3.
* The value is written using a two's complement 24-bit encoding, * The value is written using a two's complement 24-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than 3. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than 3.
*/ */
Buf writeMedium(int value); Buffer writeMedium(int value);
/** /**
* Set the given int value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given int value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using a two's complement 24-bit encoding, * The value is written using a two's complement 24-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus 3. * greater than {@link Buffer#capacity()} minus 3.
*/ */
Buf setMedium(int woff, int value); Buffer setMedium(int woff, int value);
/** /**
* Set the given unsigned int value at the current {@link Buf#writerOffset()}, * Set the given unsigned int value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by 3. * and increase the writer offset by 3.
* The value is written using an unsigned two's complement 24-bit encoding, * The value is written using an unsigned two's complement 24-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than 3. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than 3.
*/ */
Buf writeUnsignedMedium(int value); Buffer writeUnsignedMedium(int value);
/** /**
* Set the given unsigned int value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given unsigned int value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using an unsigned two's complement 24-bit encoding, * The value is written using an unsigned two's complement 24-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus 3. * greater than {@link Buffer#capacity()} minus 3.
*/ */
Buf setUnsignedMedium(int woff, int value); Buffer setUnsignedMedium(int woff, int value);
/** /**
* Get the int value at the current {@link Buf#readerOffset()}, * Get the int value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Integer#BYTES}. * and increases the reader offset by {@link Integer#BYTES}.
* The value is read using a two's complement 32-bit encoding, * The value is read using a two's complement 32-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The int value at the current reader offset. * @return The int value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Integer#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Integer#BYTES}.
*/ */
int readInt(); int readInt();
/** /**
* Get the int value at the given reader offset. * Get the int value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using a two's complement 32-bit encoding, * The value is read using a two's complement 32-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The int value at the given offset. * @return The int value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Integer#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Integer#BYTES}.
*/ */
int getInt(int roff); int getInt(int roff);
/** /**
* Get the unsigned int value at the current {@link Buf#readerOffset()}, * Get the unsigned int value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Integer#BYTES}. * and increases the reader offset by {@link Integer#BYTES}.
* The value is read using an unsigned two's complement 32-bit encoding, * The value is read using an unsigned two's complement 32-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The unsigned int value at the current reader offset. * @return The unsigned int value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Integer#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Integer#BYTES}.
*/ */
long readUnsignedInt(); long readUnsignedInt();
/** /**
* Get the unsigned int value at the given reader offset. * Get the unsigned int value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using an unsigned two's complement 32-bit encoding, * The value is read using an unsigned two's complement 32-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The unsigned int value at the given offset. * @return The unsigned int value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Integer#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Integer#BYTES}.
*/ */
long getUnsignedInt(int roff); long getUnsignedInt(int roff);
/** /**
* Set the given int value at the current {@link Buf#writerOffset()}, * Set the given int value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Integer#BYTES}. * and increase the writer offset by {@link Integer#BYTES}.
* The value is written using a two's complement 32-bit encoding, * The value is written using a two's complement 32-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Integer#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Integer#BYTES}.
*/ */
Buf writeInt(int value); Buffer writeInt(int value);
/** /**
* Set the given int value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given int value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using a two's complement 32-bit encoding, * The value is written using a two's complement 32-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The int value to write. * @param value The int value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Integer#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Integer#BYTES}.
*/ */
Buf setInt(int woff, int value); Buffer setInt(int woff, int value);
/** /**
* Set the given unsigned int value at the current {@link Buf#writerOffset()}, * Set the given unsigned int value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Integer#BYTES}. * and increase the writer offset by {@link Integer#BYTES}.
* The value is written using an unsigned two's complement 32-bit encoding, * The value is written using an unsigned two's complement 32-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The long value to write. * @param value The long value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Integer#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Integer#BYTES}.
*/ */
Buf writeUnsignedInt(long value); Buffer writeUnsignedInt(long value);
/** /**
* Set the given unsigned int value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given unsigned int value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using an unsigned two's complement 32-bit encoding, * The value is written using an unsigned two's complement 32-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The long value to write. * @param value The long value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Integer#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Integer#BYTES}.
*/ */
Buf setUnsignedInt(int woff, long value); Buffer setUnsignedInt(int woff, long value);
/** /**
* Get the float value at the current {@link Buf#readerOffset()}, * Get the float value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Float#BYTES}. * and increases the reader offset by {@link Float#BYTES}.
* The value is read using a 32-bit IEEE floating point encoding, * The value is read using a 32-bit IEEE floating point encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The float value at the current reader offset. * @return The float value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Float#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Float#BYTES}.
*/ */
float readFloat(); float readFloat();
/** /**
* Get the float value at the given reader offset. * Get the float value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using a 32-bit IEEE floating point encoding, * The value is read using a 32-bit IEEE floating point encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The float value at the given offset. * @return The float value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Float#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Float#BYTES}.
*/ */
float getFloat(int roff); float getFloat(int roff);
/** /**
* Set the given float value at the current {@link Buf#writerOffset()}, * Set the given float value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Float#BYTES}. * and increase the writer offset by {@link Float#BYTES}.
* The value is written using a 32-bit IEEE floating point encoding, * The value is written using a 32-bit IEEE floating point encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The float value to write. * @param value The float value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Float#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Float#BYTES}.
*/ */
Buf writeFloat(float value); Buffer writeFloat(float value);
/** /**
* Set the given float value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given float value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using a 32-bit IEEE floating point encoding, * The value is written using a 32-bit IEEE floating point encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The float value to write. * @param value The float value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Float#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Float#BYTES}.
*/ */
Buf setFloat(int woff, float value); Buffer setFloat(int woff, float value);
/** /**
* Get the long value at the current {@link Buf#readerOffset()}, * Get the long value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Long#BYTES}. * and increases the reader offset by {@link Long#BYTES}.
* The value is read using a two's complement 64-bit encoding, * The value is read using a two's complement 64-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The long value at the current reader offset. * @return The long value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Long#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Long#BYTES}.
*/ */
long readLong(); long readLong();
/** /**
* Get the long value at the given reader offset. * Get the long value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using a two's complement 64-bit encoding, * The value is read using a two's complement 64-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The long value at the given offset. * @return The long value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Long#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Long#BYTES}.
*/ */
long getLong(int roff); long getLong(int roff);
/** /**
* Set the given long value at the current {@link Buf#writerOffset()}, * Set the given long value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Long#BYTES}. * and increase the writer offset by {@link Long#BYTES}.
* The value is written using a two's complement 64-bit encoding, * The value is written using a two's complement 64-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The long value to write. * @param value The long value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Long#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Long#BYTES}.
*/ */
Buf writeLong(long value); Buffer writeLong(long value);
/** /**
* Set the given long value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given long value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using a two's complement 64-bit encoding, * The value is written using a two's complement 64-bit encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The long value to write. * @param value The long value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Long#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Long#BYTES}.
*/ */
Buf setLong(int woff, long value); Buffer setLong(int woff, long value);
/** /**
* Get the double value at the current {@link Buf#readerOffset()}, * Get the double value at the current {@link Buffer#readerOffset()},
* and increases the reader offset by {@link Double#BYTES}. * and increases the reader offset by {@link Double#BYTES}.
* The value is read using a 64-bit IEEE floating point encoding, * The value is read using a 64-bit IEEE floating point encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @return The double value at the current reader offset. * @return The double value at the current reader offset.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than {@link Double#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than {@link Double#BYTES}.
*/ */
double readDouble(); double readDouble();
/** /**
* Get the double value at the given reader offset. * Get the double value at the given reader offset.
* The {@link Buf#readerOffset()} is not modified. * The {@link Buffer#readerOffset()} is not modified.
* The value is read using a 64-bit IEEE floating point encoding, * The value is read using a 64-bit IEEE floating point encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param roff The read offset, an absolute offset into this buffer, to read from. * @param roff The read offset, an absolute offset into this buffer, to read from.
* @return The double value at the given offset. * @return The double value at the given offset.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Double#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Double#BYTES}.
*/ */
double getDouble(int roff); double getDouble(int roff);
/** /**
* Set the given double value at the current {@link Buf#writerOffset()}, * Set the given double value at the current {@link Buffer#writerOffset()},
* and increase the writer offset by {@link Double#BYTES}. * and increase the writer offset by {@link Double#BYTES}.
* The value is written using a 64-bit IEEE floating point encoding, * The value is written using a 64-bit IEEE floating point encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param value The double value to write. * @param value The double value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Double#BYTES}. * @throws IndexOutOfBoundsException If {@link Buffer#writableBytes} is less than {@link Double#BYTES}.
*/ */
Buf writeDouble(double value); Buffer writeDouble(double value);
/** /**
* Set the given double value at the given write offset. The {@link Buf#writerOffset()} is not modified. * Set the given double value at the given write offset. The {@link Buffer#writerOffset()} is not modified.
* The value is written using a 64-bit IEEE floating point encoding, * The value is written using a 64-bit IEEE floating point encoding,
* with the {@link Buf#order() configured} default byte order. * with the {@link Buffer#order() configured} default byte order.
* *
* @param woff The write offset, an absolute offset into this buffer to write to. * @param woff The write offset, an absolute offset into this buffer to write to.
* @param value The double value to write. * @param value The double value to write.
* @return This Buf. * @return This Buffer.
* @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or * @throws IndexOutOfBoundsException if the given offset is out of bounds of the buffer, that is, less than 0 or
* greater than {@link Buf#capacity()} minus {@link Double#BYTES}. * greater than {@link Buffer#capacity()} minus {@link Double#BYTES}.
*/ */
Buf setDouble(int woff, double value); Buffer setDouble(int woff, double value);
// </editor-fold> // </editor-fold>
} }

View File

@ -18,9 +18,9 @@ package io.netty.buffer.api;
import java.nio.ByteOrder; import java.nio.ByteOrder;
/** /**
* Interface for {@link Buf} allocators. * Interface for {@link Buffer} allocators.
*/ */
public interface Allocator extends AutoCloseable { public interface BufferAllocator extends AutoCloseable {
static void checkSize(long size) { static void checkSize(long size) {
if (size < 1) { if (size < 1) {
throw new IllegalArgumentException("Buffer size must be positive, but was " + size + '.'); throw new IllegalArgumentException("Buffer size must be positive, but was " + size + '.');
@ -34,28 +34,28 @@ public interface Allocator extends AutoCloseable {
} }
/** /**
* Allocate a {@link Buf} of the given size in bytes. This method may throw an {@link OutOfMemoryError} if there is * Allocate a {@link Buffer} of the given size in bytes. This method may throw an {@link OutOfMemoryError} if there
* not enough free memory available to allocate a {@link Buf} of the requested size. * is not enough free memory available to allocate a {@link Buffer} of the requested size.
* <p> * <p>
* The buffer will use the current platform native byte order by default, for accessor methods that don't have an * The buffer will use the current platform native byte order by default, for accessor methods that don't have an
* explicit byte order. * explicit byte order.
* *
* @param size The size of {@link Buf} to allocate. * @param size The size of {@link Buffer} to allocate.
* @return The newly allocated {@link Buf}. * @return The newly allocated {@link Buffer}.
*/ */
Buf allocate(int size); Buffer allocate(int size);
/** /**
* Allocate a {@link Buf} of the given size in bytes. This method may throw an {@link OutOfMemoryError} if there is * Allocate a {@link Buffer} of the given size in bytes. This method may throw an {@link OutOfMemoryError} if there
* not enough free memory available to allocate a {@link Buf} of the requested size. * is not enough free memory available to allocate a {@link Buffer} of the requested size.
* <p> * <p>
* The buffer will use the given byte order by default. * The buffer will use the given byte order by default.
* *
* @param size The size of {@link Buf} to allocate. * @param size The size of {@link Buffer} to allocate.
* @param order The default byte order used by the accessor methods that don't have an explicit byte order. * @param order The default byte order used by the accessor methods that don't have an explicit byte order.
* @return The newly allocated {@link Buf}. * @return The newly allocated {@link Buffer}.
*/ */
default Buf allocate(int size, ByteOrder order) { default Buffer allocate(int size, ByteOrder order) {
return allocate(size).order(order); return allocate(size).order(order);
} }
@ -68,18 +68,18 @@ public interface Allocator extends AutoCloseable {
* If the buffers are allocated for the purpose of participating in the composite buffer, * If the buffers are allocated for the purpose of participating in the composite buffer,
* then they should be closed as soon as the composite buffer has been created, like in this example: * then they should be closed as soon as the composite buffer has been created, like in this example:
* <pre>{@code * <pre>{@code
* try (Buf a = allocator.allocate(size); * try (Buffer a = allocator.allocate(size);
* Buf b = allocator.allocate(size)) { * Buffer b = allocator.allocate(size)) {
* return allocator.compose(a, b); // Reference counts for 'a' and 'b' incremented here. * return allocator.compose(a, b); // Reference counts for 'a' and 'b' incremented here.
* } // Reference count for 'a' and 'b' decremented here; composite buffer now holds the last references. * } // Reference count for 'a' and 'b' decremented here; composite buffer now holds the last references.
* }</pre> * }</pre>
* <p> * <p>
* {@linkplain Buf#send() Sending} a composite buffer implies sending all of its constituent buffers. * {@linkplain Buffer#send() Sending} a composite buffer implies sending all of its constituent buffers.
* For sending to be possible, both the composite buffer itself, and all of its constituent buffers, must be in an * For sending to be possible, both the composite buffer itself, and all of its constituent buffers, must be in an
* {@linkplain Rc#isOwned() owned state}. * {@linkplain Rc#isOwned() owned state}.
* This means that the composite buffer must be the only reference to the constituent buffers. * This means that the composite buffer must be the only reference to the constituent buffers.
* <p> * <p>
* All of the constituent buffers must have the same {@linkplain Buf#order() byte order}. * All of the constituent buffers must have the same {@linkplain Buffer#order() byte order}.
* An exception will be thrown if you attempt to compose buffers that have different byte orders, * An exception will be thrown if you attempt to compose buffers that have different byte orders,
* and changing the byte order of the constituent buffers so they become inconsistent after construction, * and changing the byte order of the constituent buffers so they become inconsistent after construction,
* will result in unspecified behaviour. * will result in unspecified behaviour.
@ -99,16 +99,17 @@ public interface Allocator extends AutoCloseable {
* <p> * <p>
* It is not a requirement that the buffers have the same size. * It is not a requirement that the buffers have the same size.
* <p> * <p>
* It is not a requirement that the buffers are allocated by this allocator, but if {@link Buf#ensureWritable(int)} * It is not a requirement that the buffers are allocated by this allocator, but if
* is called on the composed buffer, and the composed buffer needs to be expanded, then this allocator instance * {@link Buffer#ensureWritable(int)} is called on the composed buffer, and the composed buffer needs to be
* will be used for allocation the extra memory. * expanded, then this allocator instance will be used for allocation the extra memory.
* *
* @param bufs The buffers to compose into a single buffer view. * @param bufs The buffers to compose into a single buffer view.
* @return A buffer composed of, and backed by, the given buffers. * @return A buffer composed of, and backed by, the given buffers.
* @throws IllegalArgumentException if the given buffers have an inconsistent {@linkplain Buf#order() byte order}. * @throws IllegalArgumentException if the given buffers have an inconsistent
* {@linkplain Buffer#order() byte order}.
*/ */
default Buf compose(Deref<Buf>... bufs) { default Buffer compose(Deref<Buffer>... bufs) {
return new CompositeBuf(this, bufs); return new CompositeBuffer(this, bufs);
} }
/** /**
@ -122,13 +123,13 @@ public interface Allocator extends AutoCloseable {
* extension buffer. * extension buffer.
* @param extension The buffer to extend the composite buffer with. * @param extension The buffer to extend the composite buffer with.
*/ */
static void extend(Buf composite, Buf extension) { static void extend(Buffer composite, Buffer extension) {
if (!isComposite(composite)) { if (!isComposite(composite)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Expected the first buffer to be a composite buffer, " + "Expected the first buffer to be a composite buffer, " +
"but it is a " + composite.getClass() + " buffer: " + composite + '.'); "but it is a " + composite.getClass() + " buffer: " + composite + '.');
} }
CompositeBuf buf = (CompositeBuf) composite; CompositeBuffer buf = (CompositeBuffer) composite;
buf.extendWith(extension); buf.extendWith(extension);
} }
@ -137,8 +138,8 @@ public interface Allocator extends AutoCloseable {
* @param composite The buffer to check. * @param composite The buffer to check.
* @return {@code true} if the given buffer was created with {@link #compose(Deref...)}, {@code false} otherwise. * @return {@code true} if the given buffer was created with {@link #compose(Deref...)}, {@code false} otherwise.
*/ */
static boolean isComposite(Buf composite) { static boolean isComposite(Buffer composite) {
return composite.getClass() == CompositeBuf.class; return composite.getClass() == CompositeBuffer.class;
} }
/** /**
@ -149,19 +150,19 @@ public interface Allocator extends AutoCloseable {
default void close() { default void close() {
} }
static Allocator heap() { static BufferAllocator heap() {
return new ManagedAllocator(MemoryManager.getHeapMemoryManager(), Statics.CLEANER); return new ManagedBufferAllocator(MemoryManager.getHeapMemoryManager(), Statics.CLEANER);
} }
static Allocator direct() { static BufferAllocator direct() {
return new ManagedAllocator(MemoryManager.getNativeMemoryManager(), Statics.CLEANER); return new ManagedBufferAllocator(MemoryManager.getNativeMemoryManager(), Statics.CLEANER);
} }
static Allocator pooledHeap() { static BufferAllocator pooledHeap() {
return new SizeClassedMemoryPool(MemoryManager.getHeapMemoryManager()); return new SizeClassedMemoryPool(MemoryManager.getHeapMemoryManager());
} }
static Allocator pooledDirect() { static BufferAllocator pooledDirect() {
return new SizeClassedMemoryPool(MemoryManager.getNativeMemoryManager()); return new SizeClassedMemoryPool(MemoryManager.getNativeMemoryManager());
} }
} }

View File

@ -22,42 +22,42 @@ import static io.netty.buffer.api.Statics.findVarHandle;
import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodHandles.lookup;
/** /**
* The {@link BufHolder} is an abstract class that simplifies the implementation of objects that themselves contain * The {@link BufferHolder} is an abstract class that simplifies the implementation of objects that themselves contain
* a {@link Buf} instance. * a {@link Buffer} instance.
* <p> * <p>
* The {@link BufHolder} can only hold on to a single buffer, so objects and classes that need to hold on to multiple * The {@link BufferHolder} can only hold on to a single buffer, so objects and classes that need to hold on to multiple
* buffers will have to do their implementation from scratch, though they can use the code of the {@link BufHolder} as * buffers will have to do their implementation from scratch, though they can use the code of the {@link BufferHolder}
* inspiration. * as inspiration.
* <p> * <p>
* If you just want an object that is a reference to a buffer, then the {@link BufRef} can be used for that purpose. * If you just want an object that is a reference to a buffer, then the {@link BufferRef} can be used for that purpose.
* If you have an advanced use case where you wish to implement {@link Rc}, and tightly control lifetimes, then * If you have an advanced use case where you wish to implement {@link Rc}, and tightly control lifetimes, then
* {@link RcSupport} can be of help. * {@link RcSupport} can be of help.
* *
* @param <T> The concrete {@link BufHolder} type. * @param <T> The concrete {@link BufferHolder} type.
*/ */
public abstract class BufHolder<T extends BufHolder<T>> implements Rc<T> { public abstract class BufferHolder<T extends BufferHolder<T>> implements Rc<T> {
private static final VarHandle BUF = findVarHandle(lookup(), BufHolder.class, "buf", Buf.class); private static final VarHandle BUF = findVarHandle(lookup(), BufferHolder.class, "buf", Buffer.class);
private Buf buf; private Buffer buf;
/** /**
* Create a new {@link BufHolder} to hold the given {@linkplain Buf buffer}. * Create a new {@link BufferHolder} to hold the given {@linkplain Buffer buffer}.
* <p> * <p>
* <strong>Note:</strong> this increases the reference count of the given buffer. * <strong>Note:</strong> this increases the reference count of the given buffer.
* *
* @param buf The {@linkplain Buf buffer} to be held by this holder. * @param buf The {@linkplain Buffer buffer} to be held by this holder.
*/ */
protected BufHolder(Buf buf) { protected BufferHolder(Buffer buf) {
this.buf = Objects.requireNonNull(buf, "The buffer cannot be null.").acquire(); this.buf = Objects.requireNonNull(buf, "The buffer cannot be null.").acquire();
} }
/** /**
* Create a new {@link BufHolder} to hold the {@linkplain Buf buffer} received from the given {@link Send}. * Create a new {@link BufferHolder} to hold the {@linkplain Buffer buffer} received from the given {@link Send}.
* <p> * <p>
* The {@link BufHolder} will then be holding exclusive ownership of the buffer. * The {@link BufferHolder} will then be holding exclusive ownership of the buffer.
* *
* @param send The {@linkplain Buf buffer} to be held by this holder. * @param send The {@linkplain Buffer buffer} to be held by this holder.
*/ */
protected BufHolder(Send<Buf> send) { protected BufferHolder(Send<Buffer> send) {
buf = Objects.requireNonNull(send, "The send cannot be null.").receive(); buf = Objects.requireNonNull(send, "The send cannot be null.").receive();
} }
@ -90,28 +90,28 @@ public abstract class BufHolder<T extends BufHolder<T>> implements Rc<T> {
} }
/** /**
* Called when a {@linkplain #send() sent} {@link BufHolder} is received by the recipient. * Called when a {@linkplain #send() sent} {@link BufferHolder} is received by the recipient.
* The {@link BufHolder} should return a new concrete instance, that wraps the given {@link Buf} object. * The {@link BufferHolder} should return a new concrete instance, that wraps the given {@link Buffer} object.
* *
* @param buf The {@link Buf} that is {@linkplain Send#receive() received} by the recipient, * @param buf The {@link Buffer} that is {@linkplain Send#receive() received} by the recipient,
* and needs to be wrapped in a new {@link BufHolder} instance. * and needs to be wrapped in a new {@link BufferHolder} instance.
* @return A new {@linkplain T buffer holder} instance, containing the given {@linkplain Buf buffer}. * @return A new {@linkplain T buffer holder} instance, containing the given {@linkplain Buffer buffer}.
*/ */
protected abstract T receive(Buf buf); protected abstract T receive(Buffer buf);
/** /**
* Replace the underlying referenced buffer with the given buffer. * Replace the underlying referenced buffer with the given buffer.
* <p> * <p>
* This method is protected to permit advanced use cases of {@link BufHolder} sub-class implementations. * This method is protected to permit advanced use cases of {@link BufferHolder} sub-class implementations.
* <p> * <p>
* <strong>Note:</strong> this method decreases the reference count of the current buffer, * <strong>Note:</strong> this method decreases the reference count of the current buffer,
* and increases the reference count of the new buffer. * and increases the reference count of the new buffer.
* <p> * <p>
* The buffer assignment is performed using a plain store. * The buffer assignment is performed using a plain store.
* *
* @param newBuf The new {@link Buf} instance that is replacing the currently held buffer. * @param newBuf The new {@link Buffer} instance that is replacing the currently held buffer.
*/ */
protected final void replaceBuf(Buf newBuf) { protected final void replaceBuf(Buffer newBuf) {
try (var ignore = buf) { try (var ignore = buf) {
buf = newBuf.acquire(); buf = newBuf.acquire();
} }
@ -120,16 +120,16 @@ public abstract class BufHolder<T extends BufHolder<T>> implements Rc<T> {
/** /**
* Replace the underlying referenced buffer with the given buffer. * Replace the underlying referenced buffer with the given buffer.
* <p> * <p>
* This method is protected to permit advanced use cases of {@link BufHolder} sub-class implementations. * This method is protected to permit advanced use cases of {@link BufferHolder} sub-class implementations.
* <p> * <p>
* <strong>Note:</strong> this method decreases the reference count of the current buffer, * <strong>Note:</strong> this method decreases the reference count of the current buffer,
* and takes exclusive ownership of the sent buffer. * and takes exclusive ownership of the sent buffer.
* <p> * <p>
* The buffer assignment is performed using a plain store. * The buffer assignment is performed using a plain store.
* *
* @param send The new {@link Buf} instance that is replacing the currently held buffer. * @param send The new {@link Buffer} instance that is replacing the currently held buffer.
*/ */
protected final void replaceBuf(Send<Buf> send) { protected final void replaceBuf(Send<Buffer> send) {
try (var ignore = buf) { try (var ignore = buf) {
buf = send.receive(); buf = send.receive();
} }
@ -138,56 +138,56 @@ public abstract class BufHolder<T extends BufHolder<T>> implements Rc<T> {
/** /**
* Replace the underlying referenced buffer with the given buffer. * Replace the underlying referenced buffer with the given buffer.
* <p> * <p>
* This method is protected to permit advanced use cases of {@link BufHolder} sub-class implementations. * This method is protected to permit advanced use cases of {@link BufferHolder} sub-class implementations.
* <p> * <p>
* <strong>Note:</strong> this method decreases the reference count of the current buffer, * <strong>Note:</strong> this method decreases the reference count of the current buffer,
* and increases the reference count of the new buffer. * and increases the reference count of the new buffer.
* <p> * <p>
* The buffer assignment is performed using a volatile store. * The buffer assignment is performed using a volatile store.
* *
* @param newBuf The new {@link Buf} instance that is replacing the currently held buffer. * @param newBuf The new {@link Buffer} instance that is replacing the currently held buffer.
*/ */
protected final void replaceBufVolatile(Buf newBuf) { protected final void replaceBufVolatile(Buffer newBuf) {
var prev = (Buf) BUF.getAndSet(this, newBuf.acquire()); var prev = (Buffer) BUF.getAndSet(this, newBuf.acquire());
prev.close(); prev.close();
} }
/** /**
* Replace the underlying referenced buffer with the given buffer. * Replace the underlying referenced buffer with the given buffer.
* <p> * <p>
* This method is protected to permit advanced use cases of {@link BufHolder} sub-class implementations. * This method is protected to permit advanced use cases of {@link BufferHolder} sub-class implementations.
* <p> * <p>
* <strong>Note:</strong> this method decreases the reference count of the current buffer, * <strong>Note:</strong> this method decreases the reference count of the current buffer,
* and takes exclusive ownership of the sent buffer. * and takes exclusive ownership of the sent buffer.
* <p> * <p>
* The buffer assignment is performed using a volatile store. * The buffer assignment is performed using a volatile store.
* *
* @param send The {@link Send} with the new {@link Buf} instance that is replacing the currently held buffer. * @param send The {@link Send} with the new {@link Buffer} instance that is replacing the currently held buffer.
*/ */
protected final void replaceBufVolatile(Send<Buf> send) { protected final void replaceBufVolatile(Send<Buffer> send) {
var prev = (Buf) BUF.getAndSet(this, send.receive()); var prev = (Buffer) BUF.getAndSet(this, send.receive());
prev.close(); prev.close();
} }
/** /**
* Access the held {@link Buf} instance. * Access the held {@link Buffer} instance.
* <p> * <p>
* The access is performed using a plain load. * The access is performed using a plain load.
* *
* @return The {@link Buf} instance being held by this {@linkplain T buffer holder}. * @return The {@link Buffer} instance being held by this {@linkplain T buffer holder}.
*/ */
protected final Buf getBuf() { protected final Buffer getBuf() {
return buf; return buf;
} }
/** /**
* Access the held {@link Buf} instance. * Access the held {@link Buffer} instance.
* <p> * <p>
* The access is performed using a volatile load. * The access is performed using a volatile load.
* *
* @return The {@link Buf} instance being held by this {@linkplain T buffer holder}. * @return The {@link Buffer} instance being held by this {@linkplain T buffer holder}.
*/ */
protected final Buf getBufVolatile() { protected final Buffer getBufVolatile() {
return (Buf) BUF.getVolatile(this); return (Buffer) BUF.getVolatile(this);
} }
} }

View File

@ -20,16 +20,16 @@ import java.lang.invoke.VarHandle;
/** /**
* A mutable reference to a buffer. * A mutable reference to a buffer.
*/ */
public final class BufRef extends BufHolder<BufRef> { public final class BufferRef extends BufferHolder<BufferRef> {
/** /**
* Create a reference to the given {@linkplain Buf buffer}. * Create a reference to the given {@linkplain Buffer buffer}.
* This increments the reference count of the buffer. * This increments the reference count of the buffer.
* *
* @param buf The buffer to reference. * @param buf The buffer to reference.
*/ */
public BufRef(Buf buf) { public BufferRef(Buffer buf) {
super(buf); super(buf);
// BufRef is meant to be atomic, so we need to add a fence to get the semantics of a volatile store. // BufferRef is meant to be atomic, so we need to add a fence to get the semantics of a volatile store.
VarHandle.fullFence(); VarHandle.fullFence();
} }
@ -38,15 +38,15 @@ public final class BufRef extends BufHolder<BufRef> {
* *
* @param send The {@linkplain Send sent} buffer to take ownership of. * @param send The {@linkplain Send sent} buffer to take ownership of.
*/ */
public BufRef(Send<Buf> send) { public BufferRef(Send<Buffer> send) {
super(send); super(send);
// BufRef is meant to be atomic, so we need to add a fence to get the semantics of a volatile store. // BufferRef is meant to be atomic, so we need to add a fence to get the semantics of a volatile store.
VarHandle.fullFence(); VarHandle.fullFence();
} }
@Override @Override
protected BufRef receive(Buf buf) { protected BufferRef receive(Buffer buf) {
return new BufRef(buf); return new BufferRef(buf);
} }
/** /**
@ -57,9 +57,9 @@ public final class BufRef extends BufHolder<BufRef> {
* <p> * <p>
* The buffer assignment is performed using a volatile store. * The buffer assignment is performed using a volatile store.
* *
* @param newBuf The new {@link Buf} instance that is replacing the currently held buffer. * @param newBuf The new {@link Buffer} instance that is replacing the currently held buffer.
*/ */
public void replace(Buf newBuf) { public void replace(Buffer newBuf) {
replaceBufVolatile(newBuf); replaceBufVolatile(newBuf);
} }
@ -71,9 +71,9 @@ public final class BufRef extends BufHolder<BufRef> {
* <p> * <p>
* The buffer assignment is performed using a volatile store. * The buffer assignment is performed using a volatile store.
* *
* @param send The {@link Send} with the new {@link Buf} instance that is replacing the currently held buffer. * @param send The {@link Send} with the new {@link Buffer} instance that is replacing the currently held buffer.
*/ */
public void replace(Send<Buf> send) { public void replace(Send<Buffer> send) {
replaceBufVolatile(send); replaceBufVolatile(send);
} }
@ -82,7 +82,7 @@ public final class BufRef extends BufHolder<BufRef> {
* *
* @return The buffer held by the reference. * @return The buffer held by the reference.
*/ */
public Buf contents() { public Buffer contents() {
return getBufVolatile(); return getBufVolatile();
} }
} }

View File

@ -24,24 +24,24 @@ import static io.netty.buffer.api.Statics.CLEANER;
import static io.netty.buffer.api.Statics.findVarHandle; import static io.netty.buffer.api.Statics.findVarHandle;
import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodHandles.lookup;
class CleanerPooledDrop implements Drop<Buf> { class CleanerPooledDrop implements Drop<Buffer> {
private static final VarHandle CLEANABLE = private static final VarHandle CLEANABLE =
findVarHandle(lookup(), CleanerPooledDrop.class, "cleanable", GatedCleanable.class); findVarHandle(lookup(), CleanerPooledDrop.class, "cleanable", GatedCleanable.class);
private final SizeClassedMemoryPool pool; private final SizeClassedMemoryPool pool;
private final MemoryManager manager; private final MemoryManager manager;
private final Drop<Buf> delegate; private final Drop<Buffer> delegate;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private volatile GatedCleanable cleanable; private volatile GatedCleanable cleanable;
CleanerPooledDrop(SizeClassedMemoryPool pool, MemoryManager manager, CleanerPooledDrop(SizeClassedMemoryPool pool, MemoryManager manager,
Drop<Buf> delegate) { Drop<Buffer> delegate) {
this.pool = pool; this.pool = pool;
this.manager = manager; this.manager = manager;
this.delegate = delegate; this.delegate = delegate;
} }
@Override @Override
public void drop(Buf buf) { public void drop(Buffer buf) {
GatedCleanable c = (GatedCleanable) CLEANABLE.getAndSet(this, null); GatedCleanable c = (GatedCleanable) CLEANABLE.getAndSet(this, null);
if (c != null) { if (c != null) {
c.clean(); c.clean();
@ -49,7 +49,7 @@ class CleanerPooledDrop implements Drop<Buf> {
} }
@Override @Override
public void attach(Buf buf) { public void attach(Buffer buf) {
// Unregister old cleanable, if any, to avoid uncontrolled build-up. // Unregister old cleanable, if any, to avoid uncontrolled build-up.
GatedCleanable c = (GatedCleanable) CLEANABLE.getAndSet(this, null); GatedCleanable c = (GatedCleanable) CLEANABLE.getAndSet(this, null);
if (c != null) { if (c != null) {
@ -60,11 +60,11 @@ class CleanerPooledDrop implements Drop<Buf> {
var pool = this.pool; var pool = this.pool;
var mem = manager.unwrapRecoverableMemory(buf); var mem = manager.unwrapRecoverableMemory(buf);
var delegate = this.delegate; var delegate = this.delegate;
WeakReference<Buf> ref = new WeakReference<>(buf); WeakReference<Buffer> ref = new WeakReference<>(buf);
AtomicBoolean gate = new AtomicBoolean(true); AtomicBoolean gate = new AtomicBoolean(true);
cleanable = new GatedCleanable(gate, CLEANER.register(this, () -> { cleanable = new GatedCleanable(gate, CLEANER.register(this, () -> {
if (gate.getAndSet(false)) { if (gate.getAndSet(false)) {
Buf b = ref.get(); Buffer b = ref.get();
if (b == null) { if (b == null) {
pool.recoverMemory(mem); pool.recoverMemory(mem);
} else { } else {

View File

@ -18,8 +18,9 @@ package io.netty.buffer.api;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
/** /**
* This interface contain a collection of APIs used in the {@link Buf#forEachReadable(int, ReadableComponentProcessor)} * This interface contain a collection of APIs used in the
* and {@link Buf#forEachWritable(int, WritableComponentProcessor)} methods. * {@link Buffer#forEachReadable(int, ReadableComponentProcessor)} and
* {@link Buffer#forEachWritable(int, WritableComponentProcessor)} methods.
*/ */
public interface ComponentProcessor { public interface ComponentProcessor {
/** /**
@ -29,14 +30,14 @@ public interface ComponentProcessor {
interface ReadableComponentProcessor<E extends Exception> extends ComponentProcessor { interface ReadableComponentProcessor<E extends Exception> extends ComponentProcessor {
/** /**
* Process the given component at the given index in the * Process the given component at the given index in the
* {@link Buf#forEachReadable(int, ReadableComponentProcessor) iteration}. * {@link Buffer#forEachReadable(int, ReadableComponentProcessor) iteration}.
* <p> * <p>
* The component object itself is only valid during this call, but the {@link ByteBuffer byte buffers}, arrays, * The component object itself is only valid during this call, but the {@link ByteBuffer byte buffers}, arrays,
* and native address pointers obtained from it, will be valid until any * and native address pointers obtained from it, will be valid until any
* {@link Buf#isOwned() ownership} requiring operation is performed on the buffer. * {@link Buffer#isOwned() ownership} requiring operation is performed on the buffer.
* *
* @param index The current index of the given buffer component, based on the initial index passed to the * @param index The current index of the given buffer component, based on the initial index passed to the
* {@link Buf#forEachReadable(int, ReadableComponentProcessor)} method. * {@link Buffer#forEachReadable(int, ReadableComponentProcessor)} method.
* @param component The current buffer component being processed. * @param component The current buffer component being processed.
* @return {@code true} if the iteration should continue and more components should be processed, otherwise * @return {@code true} if the iteration should continue and more components should be processed, otherwise
* {@code false} to stop the iteration early. * {@code false} to stop the iteration early.
@ -51,14 +52,14 @@ public interface ComponentProcessor {
interface WritableComponentProcessor<E extends Exception> extends ComponentProcessor { interface WritableComponentProcessor<E extends Exception> extends ComponentProcessor {
/** /**
* Process the given component at the given index in the * Process the given component at the given index in the
* {@link Buf#forEachWritable(int, WritableComponentProcessor)} iteration}. * {@link Buffer#forEachWritable(int, WritableComponentProcessor)} iteration}.
* <p> * <p>
* The component object itself is only valid during this call, but the {@link ByteBuffer byte buffers}, arrays, * The component object itself is only valid during this call, but the {@link ByteBuffer byte buffers}, arrays,
* and native address pointers obtained from it, will be valid until any * and native address pointers obtained from it, will be valid until any
* {@link Buf#isOwned() ownership} requiring operation is performed on the buffer. * {@link Buffer#isOwned() ownership} requiring operation is performed on the buffer.
* *
* @param index The current index of the given buffer component, based on the initial index passed to the * @param index The current index of the given buffer component, based on the initial index passed to the
* {@link Buf#forEachWritable(int, WritableComponentProcessor)} method. * {@link Buffer#forEachWritable(int, WritableComponentProcessor)} method.
* @param component The current buffer component being processed. * @param component The current buffer component being processed.
* @return {@code true} if the iteration should continue and more components should be processed, otherwise * @return {@code true} if the iteration should continue and more components should be processed, otherwise
* {@code false} to stop the iteration early. * {@code false} to stop the iteration early.
@ -68,7 +69,7 @@ public interface ComponentProcessor {
/** /**
* A view onto the buffer component being processed in a given iteration of * A view onto the buffer component being processed in a given iteration of
* {@link Buf#forEachReadable(int, ReadableComponentProcessor)}. * {@link Buffer#forEachReadable(int, ReadableComponentProcessor)}.
*/ */
interface ReadableComponent { interface ReadableComponent {
@ -116,7 +117,8 @@ public interface ComponentProcessor {
* Get a {@link ByteBuffer} instance for this memory component. * Get a {@link ByteBuffer} instance for this memory component.
* <p> * <p>
* <strong>Note</strong> that the {@link ByteBuffer} is read-only, to prevent write accesses to the memory, * <strong>Note</strong> that the {@link ByteBuffer} is read-only, to prevent write accesses to the memory,
* when the buffer component is obtained through {@link Buf#forEachReadable(int, ReadableComponentProcessor)}. * when the buffer component is obtained through
* {@link Buffer#forEachReadable(int, ReadableComponentProcessor)}.
* *
* @return A new {@link ByteBuffer}, with its own position and limit, for this memory component. * @return A new {@link ByteBuffer}, with its own position and limit, for this memory component.
*/ */
@ -126,7 +128,7 @@ public interface ComponentProcessor {
/** /**
* A view onto the buffer component being processed in a given iteration of * A view onto the buffer component being processed in a given iteration of
* {@link Buf#forEachWritable(int, WritableComponentProcessor)}. * {@link Buffer#forEachWritable(int, WritableComponentProcessor)}.
*/ */
interface WritableComponent { interface WritableComponent {

View File

@ -27,24 +27,24 @@ import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf { final class CompositeBuffer extends RcSupport<Buffer, CompositeBuffer> implements Buffer {
/** /**
* The max array size is JVM implementation dependant, but most seem to settle on {@code Integer.MAX_VALUE - 8}. * The max array size is JVM implementation dependant, but most seem to settle on {@code Integer.MAX_VALUE - 8}.
* We set the max composite buffer capacity to the same, since it would otherwise be impossible to create a * We set the max composite buffer capacity to the same, since it would otherwise be impossible to create a
* non-composite copy of the buffer. * non-composite copy of the buffer.
*/ */
private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8; private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;
private static final Drop<CompositeBuf> COMPOSITE_DROP = buf -> { private static final Drop<CompositeBuffer> COMPOSITE_DROP = buf -> {
for (Buf b : buf.bufs) { for (Buffer b : buf.bufs) {
b.close(); b.close();
} }
buf.makeInaccessible(); buf.makeInaccessible();
}; };
private final Allocator allocator; private final BufferAllocator allocator;
private final TornBufAccessors tornBufAccessors; private final TornBufferAccessors tornBufAccessors;
private final boolean isSendable; private final boolean isSendable;
private Buf[] bufs; private Buffer[] bufs;
private int[] offsets; // The offset, for the composite buffer, where each constituent buffer starts. private int[] offsets; // The offset, for the composite buffer, where each constituent buffer starts.
private int capacity; private int capacity;
private int roff; private int roff;
@ -54,11 +54,11 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
private boolean closed; private boolean closed;
private boolean readOnly; private boolean readOnly;
CompositeBuf(Allocator allocator, Deref<Buf>[] refs) { CompositeBuffer(BufferAllocator allocator, Deref<Buffer>[] refs) {
this(allocator, true, filterExternalBufs(refs), COMPOSITE_DROP, false); this(allocator, true, filterExternalBufs(refs), COMPOSITE_DROP, false);
} }
private static Buf[] filterExternalBufs(Deref<Buf>[] refs) { private static Buffer[] filterExternalBufs(Deref<Buffer>[] refs) {
// We filter out all zero-capacity buffers because they wouldn't contribute to the composite buffer anyway, // We filter out all zero-capacity buffers because they wouldn't contribute to the composite buffer anyway,
// and also, by ensuring that all constituent buffers contribute to the size of the composite buffer, // and also, by ensuring that all constituent buffers contribute to the size of the composite buffer,
// we make sure that the number of composite buffers will never become greater than the number of bytes in // we make sure that the number of composite buffers will never become greater than the number of bytes in
@ -66,16 +66,16 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
// This restriction guarantees that methods like countComponents, forEachReadable and forEachWritable, // This restriction guarantees that methods like countComponents, forEachReadable and forEachWritable,
// will never overflow their component counts. // will never overflow their component counts.
// Allocating a new array unconditionally also prevents external modification of the array. // Allocating a new array unconditionally also prevents external modification of the array.
Buf[] bufs = Arrays.stream(refs) Buffer[] bufs = Arrays.stream(refs)
.map(r -> r.get()) // Increments reference counts. .map(r -> r.get()) // Increments reference counts.
.filter(CompositeBuf::discardEmpty) .filter(CompositeBuffer::discardEmpty)
.flatMap(CompositeBuf::flattenBuffer) .flatMap(CompositeBuffer::flattenBuffer)
.toArray(Buf[]::new); .toArray(Buffer[]::new);
// Make sure there are no duplicates among the buffers. // Make sure there are no duplicates among the buffers.
Set<Buf> duplicatesCheck = Collections.newSetFromMap(new IdentityHashMap<>()); Set<Buffer> duplicatesCheck = Collections.newSetFromMap(new IdentityHashMap<>());
duplicatesCheck.addAll(Arrays.asList(bufs)); duplicatesCheck.addAll(Arrays.asList(bufs));
if (duplicatesCheck.size() < bufs.length) { if (duplicatesCheck.size() < bufs.length) {
for (Buf buf : bufs) { for (Buffer buf : bufs) {
buf.close(); // Undo the increment we did with Deref.get(). buf.close(); // Undo the increment we did with Deref.get().
} }
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -84,7 +84,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
return bufs; return bufs;
} }
private static boolean discardEmpty(Buf buf) { private static boolean discardEmpty(Buffer buf) {
if (buf.capacity() > 0) { if (buf.capacity() > 0) {
return true; return true;
} else { } else {
@ -95,12 +95,12 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
} }
private static Stream<Buf> flattenBuffer(Buf buf) { private static Stream<Buffer> flattenBuffer(Buffer buf) {
if (buf instanceof CompositeBuf) { if (buf instanceof CompositeBuffer) {
// Extract components and move our reference count from the composite onto the components. // Extract components and move our reference count from the composite onto the components.
var composite = (CompositeBuf) buf; var composite = (CompositeBuffer) buf;
var bufs = composite.bufs; var bufs = composite.bufs;
for (Buf b : bufs) { for (Buffer b : bufs) {
b.acquire(); b.acquire();
} }
buf.close(); // Important: acquire on components *before* closing composite. buf.close(); // Important: acquire on components *before* closing composite.
@ -109,20 +109,20 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
return Stream.of(buf); return Stream.of(buf);
} }
private CompositeBuf(Allocator allocator, boolean isSendable, Buf[] bufs, Drop<CompositeBuf> drop, private CompositeBuffer(BufferAllocator allocator, boolean isSendable, Buffer[] bufs, Drop<CompositeBuffer> drop,
boolean acquireBufs) { boolean acquireBufs) {
super(drop); super(drop);
this.allocator = allocator; this.allocator = allocator;
this.isSendable = isSendable; this.isSendable = isSendable;
if (acquireBufs) { if (acquireBufs) {
for (Buf buf : bufs) { for (Buffer buf : bufs) {
buf.acquire(); buf.acquire();
} }
} }
try { try {
if (bufs.length > 0) { if (bufs.length > 0) {
ByteOrder targetOrder = bufs[0].order(); ByteOrder targetOrder = bufs[0].order();
for (Buf buf : bufs) { for (Buffer buf : bufs) {
if (buf.order() != targetOrder) { if (buf.order() != targetOrder) {
throw new IllegalArgumentException("Constituent buffers have inconsistent byte order."); throw new IllegalArgumentException("Constituent buffers have inconsistent byte order.");
} }
@ -130,7 +130,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
order = bufs[0].order(); order = bufs[0].order();
boolean targetReadOnly = bufs[0].readOnly(); boolean targetReadOnly = bufs[0].readOnly();
for (Buf buf : bufs) { for (Buffer buf : bufs) {
if (buf.readOnly() != targetReadOnly) { if (buf.readOnly() != targetReadOnly) {
throw new IllegalArgumentException("Constituent buffers have inconsistent read-only state."); throw new IllegalArgumentException("Constituent buffers have inconsistent read-only state.");
} }
@ -141,11 +141,11 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
this.bufs = bufs; this.bufs = bufs;
computeBufferOffsets(); computeBufferOffsets();
tornBufAccessors = new TornBufAccessors(this); tornBufAccessors = new TornBufferAccessors(this);
} catch (Exception e) { } catch (Exception e) {
// Always close bufs on exception, regardless of acquireBufs value. // Always close bufs on exception, regardless of acquireBufs value.
// If acquireBufs is false, it just means the ref count increments happened prior to this constructor call. // If acquireBufs is false, it just means the ref count increments happened prior to this constructor call.
for (Buf buf : bufs) { for (Buffer buf : bufs) {
buf.close(); buf.close();
} }
throw e; throw e;
@ -157,7 +157,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
int woff = 0; int woff = 0;
int roff = 0; int roff = 0;
boolean woffMidpoint = false; boolean woffMidpoint = false;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
if (buf.writableBytes() == 0) { if (buf.writableBytes() == 0) {
woff += buf.capacity(); woff += buf.capacity();
} else if (!woffMidpoint) { } else if (!woffMidpoint) {
@ -170,7 +170,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
} }
boolean roffMidpoint = false; boolean roffMidpoint = false;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
if (buf.readableBytes() == 0 && buf.writableBytes() == 0) { if (buf.readableBytes() == 0 && buf.writableBytes() == 0) {
roff += buf.capacity(); roff += buf.capacity();
} else if (!roffMidpoint) { } else if (!roffMidpoint) {
@ -206,14 +206,14 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@Override @Override
public String toString() { public String toString() {
return "Buf[roff:" + roff + ", woff:" + woff + ", cap:" + capacity + ']'; return "Buffer[roff:" + roff + ", woff:" + woff + ", cap:" + capacity + ']';
} }
@Override @Override
public Buf order(ByteOrder order) { public Buffer order(ByteOrder order) {
if (this.order != order) { if (this.order != order) {
this.order = order; this.order = order;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
buf.order(order); buf.order(order);
} }
} }
@ -236,10 +236,10 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf readerOffset(int index) { public Buffer readerOffset(int index) {
prepRead(index, 0); prepRead(index, 0);
int indexLeft = index; int indexLeft = index;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
buf.readerOffset(Math.min(indexLeft, buf.capacity())); buf.readerOffset(Math.min(indexLeft, buf.capacity()));
indexLeft = Math.max(0, indexLeft - buf.capacity()); indexLeft = Math.max(0, indexLeft - buf.capacity());
} }
@ -253,10 +253,10 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writerOffset(int index) { public Buffer writerOffset(int index) {
checkWriteBounds(index, 0); checkWriteBounds(index, 0);
int indexLeft = index; int indexLeft = index;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
buf.writerOffset(Math.min(indexLeft, buf.capacity())); buf.writerOffset(Math.min(indexLeft, buf.capacity()));
indexLeft = Math.max(0, indexLeft - buf.capacity()); indexLeft = Math.max(0, indexLeft - buf.capacity());
} }
@ -265,8 +265,8 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf fill(byte value) { public Buffer fill(byte value) {
for (Buf buf : bufs) { for (Buffer buf : bufs) {
buf.fill(value); buf.fill(value);
} }
return this; return this;
@ -278,8 +278,8 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf readOnly(boolean readOnly) { public Buffer readOnly(boolean readOnly) {
for (Buf buf : bufs) { for (Buffer buf : bufs) {
buf.readOnly(readOnly); buf.readOnly(readOnly);
} }
this.readOnly = readOnly; this.readOnly = readOnly;
@ -292,24 +292,24 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf slice(int offset, int length) { public Buffer slice(int offset, int length) {
checkWriteBounds(offset, length); checkWriteBounds(offset, length);
if (offset < 0 || length < 0) { if (offset < 0 || length < 0) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Offset and length cannot be negative, but offset was " + "Offset and length cannot be negative, but offset was " +
offset + ", and length was " + length + '.'); offset + ", and length was " + length + '.');
} }
Buf choice = (Buf) chooseBuffer(offset, 0); Buffer choice = (Buffer) chooseBuffer(offset, 0);
Buf[] slices = null; Buffer[] slices = null;
acquire(); // Increase reference count of the original composite buffer. acquire(); // Increase reference count of the original composite buffer.
Drop<CompositeBuf> drop = obj -> { Drop<CompositeBuffer> drop = obj -> {
close(); // Decrement the reference count of the original composite buffer. close(); // Decrement the reference count of the original composite buffer.
COMPOSITE_DROP.drop(obj); COMPOSITE_DROP.drop(obj);
}; };
try { try {
if (length > 0) { if (length > 0) {
slices = new Buf[bufs.length]; slices = new Buffer[bufs.length];
int off = subOffset; int off = subOffset;
int cap = length; int cap = length;
int i; int i;
@ -323,17 +323,17 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
slices = Arrays.copyOf(slices, i); slices = Arrays.copyOf(slices, i);
} else { } else {
// Specialize for length == 0, since we must slice from at least one constituent buffer. // Specialize for length == 0, since we must slice from at least one constituent buffer.
slices = new Buf[] { choice.slice(subOffset, 0) }; slices = new Buffer[] { choice.slice(subOffset, 0) };
} }
return new CompositeBuf(allocator, false, slices, drop, true); return new CompositeBuffer(allocator, false, slices, drop, true);
} catch (Throwable throwable) { } catch (Throwable throwable) {
// We called acquire prior to the try-clause. We need to undo that if we're not creating a composite buffer: // We called acquire prior to the try-clause. We need to undo that if we're not creating a composite buffer:
close(); close();
throw throwable; throw throwable;
} finally { } finally {
if (slices != null) { if (slices != null) {
for (Buf slice : slices) { for (Buffer slice : slices) {
if (slice != null) { if (slice != null) {
slice.close(); // Ownership now transfers to the composite buffer. slice.close(); // Ownership now transfers to the composite buffer.
} }
@ -363,7 +363,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
throw indexOutOfBounds(srcPos + length, false); throw indexOutOfBounds(srcPos + length, false);
} }
while (length > 0) { while (length > 0) {
var buf = (Buf) chooseBuffer(srcPos, 0); var buf = (Buffer) chooseBuffer(srcPos, 0);
int toCopy = Math.min(buf.capacity() - subOffset, length); int toCopy = Math.min(buf.capacity() - subOffset, length);
dest.copyInto(buf, subOffset, destPos, toCopy); dest.copyInto(buf, subOffset, destPos, toCopy);
srcPos += toCopy; srcPos += toCopy;
@ -374,11 +374,11 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@FunctionalInterface @FunctionalInterface
private interface CopyInto { private interface CopyInto {
void copyInto(Buf src, int srcPos, int destPos, int length); void copyInto(Buffer src, int srcPos, int destPos, int length);
} }
@Override @Override
public void copyInto(int srcPos, Buf dest, int destPos, int length) { public void copyInto(int srcPos, Buffer dest, int destPos, int length) {
if (length < 0) { if (length < 0) {
throw new IndexOutOfBoundsException("Length cannot be negative: " + length + '.'); throw new IndexOutOfBoundsException("Length cannot be negative: " + length + '.');
} }
@ -422,7 +422,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
int startBufferIndex = searchOffsets(fromOffset); int startBufferIndex = searchOffsets(fromOffset);
int off = fromOffset - offsets[startBufferIndex]; int off = fromOffset - offsets[startBufferIndex];
Buf startBuf = bufs[startBufferIndex]; Buffer startBuf = bufs[startBufferIndex];
ByteCursor startCursor = startBuf.openCursor(off, Math.min(startBuf.capacity() - off, length)); ByteCursor startCursor = startBuf.openCursor(off, Math.min(startBuf.capacity() - off, length));
return new ByteCursor() { return new ByteCursor() {
int index = fromOffset; int index = fromOffset;
@ -484,7 +484,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
private void nextCursor() { private void nextCursor() {
bufferIndex++; bufferIndex++;
Buf nextBuf = bufs[bufferIndex]; Buffer nextBuf = bufs[bufferIndex];
cursor = nextBuf.openCursor(0, Math.min(nextBuf.capacity(), bytesLeft())); cursor = nextBuf.openCursor(0, Math.min(nextBuf.capacity(), bytesLeft()));
initOffset = 0; initOffset = 0;
} }
@ -523,7 +523,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
int startBufferIndex = searchOffsets(fromOffset); int startBufferIndex = searchOffsets(fromOffset);
int off = fromOffset - offsets[startBufferIndex]; int off = fromOffset - offsets[startBufferIndex];
Buf startBuf = bufs[startBufferIndex]; Buffer startBuf = bufs[startBufferIndex];
ByteCursor startCursor = startBuf.openReverseCursor(off, Math.min(off + 1, length)); ByteCursor startCursor = startBuf.openReverseCursor(off, Math.min(off + 1, length));
return new ByteCursor() { return new ByteCursor() {
int index = fromOffset; int index = fromOffset;
@ -585,7 +585,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
private void nextCursor() { private void nextCursor() {
bufferIndex--; bufferIndex--;
Buf nextBuf = bufs[bufferIndex]; Buffer nextBuf = bufs[bufferIndex];
int length = Math.min(nextBuf.capacity(), bytesLeft()); int length = Math.min(nextBuf.capacity(), bytesLeft());
int offset = nextBuf.capacity() - 1; int offset = nextBuf.capacity() - 1;
cursor = nextBuf.openReverseCursor(offset, length); cursor = nextBuf.openReverseCursor(offset, length);
@ -632,23 +632,23 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
// Let's see if we can solve some or all of the requested size with compaction. // Let's see if we can solve some or all of the requested size with compaction.
// We always compact as much as is possible, regardless of size. This amortizes our work. // We always compact as much as is possible, regardless of size. This amortizes our work.
int compactableBuffers = 0; int compactableBuffers = 0;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
if (buf.capacity() != buf.readerOffset()) { if (buf.capacity() != buf.readerOffset()) {
break; break;
} }
compactableBuffers++; compactableBuffers++;
} }
if (compactableBuffers > 0) { if (compactableBuffers > 0) {
Buf[] compactable; Buffer[] compactable;
if (compactableBuffers < bufs.length) { if (compactableBuffers < bufs.length) {
compactable = new Buf[compactableBuffers]; compactable = new Buffer[compactableBuffers];
System.arraycopy(bufs, 0, compactable, 0, compactable.length); System.arraycopy(bufs, 0, compactable, 0, compactable.length);
System.arraycopy(bufs, compactable.length, bufs, 0, bufs.length - compactable.length); System.arraycopy(bufs, compactable.length, bufs, 0, bufs.length - compactable.length);
System.arraycopy(compactable, 0, bufs, bufs.length - compactable.length, compactable.length); System.arraycopy(compactable, 0, bufs, bufs.length - compactable.length, compactable.length);
} else { } else {
compactable = bufs; compactable = bufs;
} }
for (Buf buf : compactable) { for (Buffer buf : compactable) {
buf.reset(); buf.reset();
} }
computeBufferOffsets(); computeBufferOffsets();
@ -660,13 +660,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
long newSize = capacity() + (long) size; long newSize = capacity() + (long) size;
Allocator.checkSize(newSize); BufferAllocator.checkSize(newSize);
int growth = size - writableBytes(); int growth = size - writableBytes();
Buf extension = bufs.length == 0? allocator.allocate(growth) : allocator.allocate(growth, order()); Buffer extension = bufs.length == 0? allocator.allocate(growth) : allocator.allocate(growth, order());
unsafeExtendWith(extension); unsafeExtendWith(extension);
} }
void extendWith(Buf extension) { void extendWith(Buffer extension) {
Objects.requireNonNull(extension, "Extension buffer cannot be null."); Objects.requireNonNull(extension, "Extension buffer cannot be null.");
if (!isOwned()) { if (!isOwned()) {
throw new IllegalStateException("This buffer cannot be extended because it is not in an owned state."); throw new IllegalStateException("This buffer cannot be extended because it is not in an owned state.");
@ -693,22 +693,22 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
long newSize = capacity() + extensionCapacity; long newSize = capacity() + extensionCapacity;
Allocator.checkSize(newSize); BufferAllocator.checkSize(newSize);
Buf[] restoreTemp = bufs; // We need this to restore our buffer array, in case offset computations fail. Buffer[] restoreTemp = bufs; // We need this to restore our buffer array, in case offset computations fail.
try { try {
if (extension instanceof CompositeBuf) { if (extension instanceof CompositeBuffer) {
// If the extension is itself a composite buffer, then extend this one by all of the constituent // If the extension is itself a composite buffer, then extend this one by all of the constituent
// component buffers. // component buffers.
CompositeBuf compositeExtension = (CompositeBuf) extension; CompositeBuffer compositeExtension = (CompositeBuffer) extension;
Buf[] addedBuffers = compositeExtension.bufs; Buffer[] addedBuffers = compositeExtension.bufs;
Set<Buf> duplicatesCheck = Collections.newSetFromMap(new IdentityHashMap<>()); Set<Buffer> duplicatesCheck = Collections.newSetFromMap(new IdentityHashMap<>());
duplicatesCheck.addAll(Arrays.asList(bufs)); duplicatesCheck.addAll(Arrays.asList(bufs));
duplicatesCheck.addAll(Arrays.asList(addedBuffers)); duplicatesCheck.addAll(Arrays.asList(addedBuffers));
if (duplicatesCheck.size() < bufs.length + addedBuffers.length) { if (duplicatesCheck.size() < bufs.length + addedBuffers.length) {
throw extensionDuplicatesException(); throw extensionDuplicatesException();
} }
for (Buf addedBuffer : addedBuffers) { for (Buffer addedBuffer : addedBuffers) {
addedBuffer.acquire(); addedBuffer.acquire();
} }
int extendAtIndex = bufs.length; int extendAtIndex = bufs.length;
@ -716,7 +716,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
System.arraycopy(addedBuffers, 0, bufs, extendAtIndex, addedBuffers.length); System.arraycopy(addedBuffers, 0, bufs, extendAtIndex, addedBuffers.length);
computeBufferOffsets(); computeBufferOffsets();
} else { } else {
for (Buf buf : restoreTemp) { for (Buffer buf : restoreTemp) {
if (buf == extension) { if (buf == extension) {
throw extensionDuplicatesException(); throw extensionDuplicatesException();
} }
@ -739,37 +739,37 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
" as it would cause the buffer to have duplicate constituent buffers."); " as it would cause the buffer to have duplicate constituent buffers.");
} }
private void unsafeExtendWith(Buf extension) { private void unsafeExtendWith(Buffer extension) {
bufs = Arrays.copyOf(bufs, bufs.length + 1); bufs = Arrays.copyOf(bufs, bufs.length + 1);
bufs[bufs.length - 1] = extension; bufs[bufs.length - 1] = extension;
computeBufferOffsets(); computeBufferOffsets();
} }
@Override @Override
public Buf bifurcate() { public Buffer bifurcate() {
if (!isOwned()) { if (!isOwned()) {
throw new IllegalStateException("Cannot bifurcate a buffer that is not owned."); throw new IllegalStateException("Cannot bifurcate a buffer that is not owned.");
} }
if (bufs.length == 0) { if (bufs.length == 0) {
// Bifurcating a zero-length buffer is trivial. // Bifurcating a zero-length buffer is trivial.
return new CompositeBuf(allocator, true, bufs, unsafeGetDrop(), true).order(order); return new CompositeBuffer(allocator, true, bufs, unsafeGetDrop(), true).order(order);
} }
int i = searchOffsets(woff); int i = searchOffsets(woff);
int off = woff - offsets[i]; int off = woff - offsets[i];
Buf[] bifs = Arrays.copyOf(bufs, off == 0? i : 1 + i); Buffer[] bifs = Arrays.copyOf(bufs, off == 0? i : 1 + i);
bufs = Arrays.copyOfRange(bufs, off == bufs[i].capacity()? 1 + i : i, bufs.length); bufs = Arrays.copyOfRange(bufs, off == bufs[i].capacity()? 1 + i : i, bufs.length);
if (off > 0 && bifs.length > 0 && off < bifs[bifs.length - 1].capacity()) { if (off > 0 && bifs.length > 0 && off < bifs[bifs.length - 1].capacity()) {
bifs[bifs.length - 1] = bufs[0].bifurcate(); bifs[bifs.length - 1] = bufs[0].bifurcate();
} }
computeBufferOffsets(); computeBufferOffsets();
try { try {
var compositeBuf = new CompositeBuf(allocator, true, bifs, unsafeGetDrop(), true); var compositeBuf = new CompositeBuffer(allocator, true, bifs, unsafeGetDrop(), true);
compositeBuf.order = order; // Preserve byte order even if bifs array is empty. compositeBuf.order = order; // Preserve byte order even if bifs array is empty.
return compositeBuf; return compositeBuf;
} finally { } finally {
// Drop our references to the buffers in the bifs array. They belong to the new composite buffer now. // Drop our references to the buffers in the bifs array. They belong to the new composite buffer now.
for (Buf bif : bifs) { for (Buffer bif : bifs) {
bif.close(); bif.close();
} }
} }
@ -810,7 +810,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@Override @Override
public int countComponents() { public int countComponents() {
int sum = 0; int sum = 0;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
sum += buf.countComponents(); sum += buf.countComponents();
} }
return sum; return sum;
@ -819,7 +819,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@Override @Override
public int countReadableComponents() { public int countReadableComponents() {
int sum = 0; int sum = 0;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
sum += buf.countReadableComponents(); sum += buf.countReadableComponents();
} }
return sum; return sum;
@ -828,7 +828,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@Override @Override
public int countWritableComponents() { public int countWritableComponents() {
int sum = 0; int sum = 0;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
sum += buf.countWritableComponents(); sum += buf.countWritableComponents();
} }
return sum; return sum;
@ -839,7 +839,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
throws E { throws E {
checkReadBounds(readerOffset(), Math.max(1, readableBytes())); checkReadBounds(readerOffset(), Math.max(1, readableBytes()));
int visited = 0; int visited = 0;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
if (buf.readableBytes() > 0) { if (buf.readableBytes() > 0) {
int count = buf.forEachReadable(visited + initialIndex, processor); int count = buf.forEachReadable(visited + initialIndex, processor);
if (count > 0) { if (count > 0) {
@ -858,7 +858,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
throws E { throws E {
checkWriteBounds(writerOffset(), Math.max(1, writableBytes())); checkWriteBounds(writerOffset(), Math.max(1, writableBytes()));
int visited = 0; int visited = 0;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
if (buf.writableBytes() > 0) { if (buf.writableBytes() > 0) {
int count = buf.forEachWritable(visited + initialIndex, processor); int count = buf.forEachWritable(visited + initialIndex, processor);
if (count > 0) { if (count > 0) {
@ -894,25 +894,25 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeByte(byte value) { public Buffer writeByte(byte value) {
prepWrite(Byte.BYTES).writeByte(value); prepWrite(Byte.BYTES).writeByte(value);
return this; return this;
} }
@Override @Override
public Buf setByte(int woff, byte value) { public Buffer setByte(int woff, byte value) {
prepWrite(woff, Byte.BYTES).setByte(subOffset, value); prepWrite(woff, Byte.BYTES).setByte(subOffset, value);
return this; return this;
} }
@Override @Override
public Buf writeUnsignedByte(int value) { public Buffer writeUnsignedByte(int value) {
prepWrite(Byte.BYTES).writeUnsignedByte(value); prepWrite(Byte.BYTES).writeUnsignedByte(value);
return this; return this;
} }
@Override @Override
public Buf setUnsignedByte(int woff, int value) { public Buffer setUnsignedByte(int woff, int value) {
prepWrite(woff, Byte.BYTES).setUnsignedByte(subOffset, value); prepWrite(woff, Byte.BYTES).setUnsignedByte(subOffset, value);
return this; return this;
} }
@ -928,13 +928,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeChar(char value) { public Buffer writeChar(char value) {
prepWrite(2).writeChar(value); prepWrite(2).writeChar(value);
return this; return this;
} }
@Override @Override
public Buf setChar(int woff, char value) { public Buffer setChar(int woff, char value) {
prepWrite(woff, 2).setChar(subOffset, value); prepWrite(woff, 2).setChar(subOffset, value);
return this; return this;
} }
@ -960,25 +960,25 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeShort(short value) { public Buffer writeShort(short value) {
prepWrite(Short.BYTES).writeShort(value); prepWrite(Short.BYTES).writeShort(value);
return this; return this;
} }
@Override @Override
public Buf setShort(int woff, short value) { public Buffer setShort(int woff, short value) {
prepWrite(woff, Short.BYTES).setShort(subOffset, value); prepWrite(woff, Short.BYTES).setShort(subOffset, value);
return this; return this;
} }
@Override @Override
public Buf writeUnsignedShort(int value) { public Buffer writeUnsignedShort(int value) {
prepWrite(Short.BYTES).writeUnsignedShort(value); prepWrite(Short.BYTES).writeUnsignedShort(value);
return this; return this;
} }
@Override @Override
public Buf setUnsignedShort(int woff, int value) { public Buffer setUnsignedShort(int woff, int value) {
prepWrite(woff, Short.BYTES).setUnsignedShort(subOffset, value); prepWrite(woff, Short.BYTES).setUnsignedShort(subOffset, value);
return this; return this;
} }
@ -1004,25 +1004,25 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeMedium(int value) { public Buffer writeMedium(int value) {
prepWrite(3).writeMedium(value); prepWrite(3).writeMedium(value);
return this; return this;
} }
@Override @Override
public Buf setMedium(int woff, int value) { public Buffer setMedium(int woff, int value) {
prepWrite(woff, 3).setMedium(subOffset, value); prepWrite(woff, 3).setMedium(subOffset, value);
return this; return this;
} }
@Override @Override
public Buf writeUnsignedMedium(int value) { public Buffer writeUnsignedMedium(int value) {
prepWrite(3).writeUnsignedMedium(value); prepWrite(3).writeUnsignedMedium(value);
return this; return this;
} }
@Override @Override
public Buf setUnsignedMedium(int woff, int value) { public Buffer setUnsignedMedium(int woff, int value) {
prepWrite(woff, 3).setUnsignedMedium(subOffset, value); prepWrite(woff, 3).setUnsignedMedium(subOffset, value);
return this; return this;
} }
@ -1048,25 +1048,25 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeInt(int value) { public Buffer writeInt(int value) {
prepWrite(Integer.BYTES).writeInt(value); prepWrite(Integer.BYTES).writeInt(value);
return this; return this;
} }
@Override @Override
public Buf setInt(int woff, int value) { public Buffer setInt(int woff, int value) {
prepWrite(woff, Integer.BYTES).setInt(subOffset, value); prepWrite(woff, Integer.BYTES).setInt(subOffset, value);
return this; return this;
} }
@Override @Override
public Buf writeUnsignedInt(long value) { public Buffer writeUnsignedInt(long value) {
prepWrite(Integer.BYTES).writeUnsignedInt(value); prepWrite(Integer.BYTES).writeUnsignedInt(value);
return this; return this;
} }
@Override @Override
public Buf setUnsignedInt(int woff, long value) { public Buffer setUnsignedInt(int woff, long value) {
prepWrite(woff, Integer.BYTES).setUnsignedInt(subOffset, value); prepWrite(woff, Integer.BYTES).setUnsignedInt(subOffset, value);
return this; return this;
} }
@ -1082,13 +1082,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeFloat(float value) { public Buffer writeFloat(float value) {
prepWrite(Float.BYTES).writeFloat(value); prepWrite(Float.BYTES).writeFloat(value);
return this; return this;
} }
@Override @Override
public Buf setFloat(int woff, float value) { public Buffer setFloat(int woff, float value) {
prepWrite(woff, Float.BYTES).setFloat(subOffset, value); prepWrite(woff, Float.BYTES).setFloat(subOffset, value);
return this; return this;
} }
@ -1104,13 +1104,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeLong(long value) { public Buffer writeLong(long value) {
prepWrite(Long.BYTES).writeLong(value); prepWrite(Long.BYTES).writeLong(value);
return this; return this;
} }
@Override @Override
public Buf setLong(int woff, long value) { public Buffer setLong(int woff, long value) {
prepWrite(woff, Long.BYTES).setLong(subOffset, value); prepWrite(woff, Long.BYTES).setLong(subOffset, value);
return this; return this;
} }
@ -1126,22 +1126,22 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeDouble(double value) { public Buffer writeDouble(double value) {
prepWrite(Double.BYTES).writeDouble(value); prepWrite(Double.BYTES).writeDouble(value);
return this; return this;
} }
@Override @Override
public Buf setDouble(int woff, double value) { public Buffer setDouble(int woff, double value) {
prepWrite(woff, Double.BYTES).setDouble(subOffset, value); prepWrite(woff, Double.BYTES).setDouble(subOffset, value);
return this; return this;
} }
// </editor-fold> // </editor-fold>
@Override @Override
protected Owned<CompositeBuf> prepareSend() { protected Owned<CompositeBuffer> prepareSend() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Send<Buf>[] sends = new Send[bufs.length]; Send<Buffer>[] sends = new Send[bufs.length];
try { try {
for (int i = 0; i < bufs.length; i++) { for (int i = 0; i < bufs.length; i++) {
sends[i] = bufs[i].send(); sends[i] = bufs[i].send();
@ -1160,14 +1160,14 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
throw throwable; throw throwable;
} }
makeInaccessible(); makeInaccessible();
return new Owned<CompositeBuf>() { return new Owned<CompositeBuffer>() {
@Override @Override
public CompositeBuf transferOwnership(Drop<CompositeBuf> drop) { public CompositeBuffer transferOwnership(Drop<CompositeBuffer> drop) {
Buf[] received = new Buf[sends.length]; Buffer[] received = new Buffer[sends.length];
for (int i = 0; i < sends.length; i++) { for (int i = 0; i < sends.length; i++) {
received[i] = sends[i].receive(); received[i] = sends[i].receive();
} }
var composite = new CompositeBuf(allocator, true, received, drop, true); var composite = new CompositeBuffer(allocator, true, received, drop, true);
composite.readOnly = readOnly; composite.readOnly = readOnly;
drop.attach(composite); drop.attach(composite);
return composite; return composite;
@ -1198,7 +1198,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
private boolean allConstituentsAreOwned() { private boolean allConstituentsAreOwned() {
boolean result = true; boolean result = true;
for (Buf buf : bufs) { for (Buffer buf : bufs) {
result &= buf.isOwned(); result &= buf.isOwned();
} }
return result; return result;
@ -1228,13 +1228,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
buf.setUnsignedByte(subOffset, value); buf.setUnsignedByte(subOffset, value);
} }
private BufAccessors prepRead(int size) { private BufferAccessors prepRead(int size) {
var buf = prepRead(roff, size); var buf = prepRead(roff, size);
roff += size; roff += size;
return buf; return buf;
} }
private BufAccessors prepRead(int index, int size) { private BufferAccessors prepRead(int index, int size) {
checkReadBounds(index, size); checkReadBounds(index, size);
return chooseBuffer(index, size); return chooseBuffer(index, size);
} }
@ -1245,13 +1245,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
} }
private BufAccessors prepWrite(int size) { private BufferAccessors prepWrite(int size) {
var buf = prepWrite(woff, size); var buf = prepWrite(woff, size);
woff += size; woff += size;
return buf; return buf;
} }
private BufAccessors prepWrite(int index, int size) { private BufferAccessors prepWrite(int index, int size) {
checkWriteBounds(index, size); checkWriteBounds(index, size);
return chooseBuffer(index, size); return chooseBuffer(index, size);
} }
@ -1282,7 +1282,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
return new IllegalStateException("This buffer is read-only."); return new IllegalStateException("This buffer is read-only.");
} }
private BufAccessors chooseBuffer(int index, int size) { private BufferAccessors chooseBuffer(int index, int size) {
int i = searchOffsets(index); int i = searchOffsets(index);
if (i == bufs.length) { if (i == bufs.length) {
// This happens when the read/write offsets are parked 1 byte beyond the end of the buffer. // This happens when the read/write offsets are parked 1 byte beyond the end of the buffer.
@ -1290,7 +1290,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
return null; return null;
} }
int off = index - offsets[i]; int off = index - offsets[i];
Buf candidate = bufs[i]; Buffer candidate = bufs[i];
if (off + size <= candidate.capacity()) { if (off + size <= candidate.capacity()) {
subOffset = off; subOffset = off;
return candidate; return candidate;
@ -1299,7 +1299,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
return tornBufAccessors; return tornBufAccessors;
} }
private BufAccessors choosePassThroughBuffer(int index) { private BufferAccessors choosePassThroughBuffer(int index) {
int i = searchOffsets(index); int i = searchOffsets(index);
return bufs[i]; return bufs[i];
} }
@ -1310,10 +1310,10 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
// <editor-fold defaultstate="collapsed" desc="Torn buffer access."> // <editor-fold defaultstate="collapsed" desc="Torn buffer access.">
private static final class TornBufAccessors implements BufAccessors { private static final class TornBufferAccessors implements BufferAccessors {
private final CompositeBuf buf; private final CompositeBuffer buf;
private TornBufAccessors(CompositeBuf buf) { private TornBufferAccessors(CompositeBuffer buf) {
this.buf = buf; this.buf = buf;
} }
@ -1338,22 +1338,22 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeByte(byte value) { public Buffer writeByte(byte value) {
throw new AssertionError("Method should not be used."); throw new AssertionError("Method should not be used.");
} }
@Override @Override
public Buf setByte(int woff, byte value) { public Buffer setByte(int woff, byte value) {
throw new AssertionError("Method should not be used."); throw new AssertionError("Method should not be used.");
} }
@Override @Override
public Buf writeUnsignedByte(int value) { public Buffer writeUnsignedByte(int value) {
throw new AssertionError("Method should not be used."); throw new AssertionError("Method should not be used.");
} }
@Override @Override
public Buf setUnsignedByte(int woff, int value) { public Buffer setUnsignedByte(int woff, int value) {
throw new AssertionError("Method should not be used."); throw new AssertionError("Method should not be used.");
} }
@ -1376,7 +1376,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeChar(char value) { public Buffer writeChar(char value) {
if (bigEndian()) { if (bigEndian()) {
write(value >>> 8); write(value >>> 8);
write(value & 0xFF); write(value & 0xFF);
@ -1388,7 +1388,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf setChar(int woff, char value) { public Buffer setChar(int woff, char value) {
if (bigEndian()) { if (bigEndian()) {
write(woff, value >>> 8); write(woff, value >>> 8);
write(woff + 1, value & 0xFF); write(woff + 1, value & 0xFF);
@ -1436,7 +1436,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeShort(short value) { public Buffer writeShort(short value) {
if (bigEndian()) { if (bigEndian()) {
write(value >>> 8); write(value >>> 8);
write(value & 0xFF); write(value & 0xFF);
@ -1448,7 +1448,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf setShort(int woff, short value) { public Buffer setShort(int woff, short value) {
if (bigEndian()) { if (bigEndian()) {
write(woff, value >>> 8); write(woff, value >>> 8);
write(woff + 1, value & 0xFF); write(woff + 1, value & 0xFF);
@ -1460,7 +1460,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeUnsignedShort(int value) { public Buffer writeUnsignedShort(int value) {
if (bigEndian()) { if (bigEndian()) {
write(value >>> 8); write(value >>> 8);
write(value & 0xFF); write(value & 0xFF);
@ -1472,7 +1472,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf setUnsignedShort(int woff, int value) { public Buffer setUnsignedShort(int woff, int value) {
if (bigEndian()) { if (bigEndian()) {
write(woff, value >>> 8); write(woff, value >>> 8);
write(woff + 1, value & 0xFF); write(woff + 1, value & 0xFF);
@ -1520,7 +1520,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeMedium(int value) { public Buffer writeMedium(int value) {
if (bigEndian()) { if (bigEndian()) {
write(value >>> 16); write(value >>> 16);
write(value >>> 8 & 0xFF); write(value >>> 8 & 0xFF);
@ -1534,7 +1534,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf setMedium(int woff, int value) { public Buffer setMedium(int woff, int value) {
if (bigEndian()) { if (bigEndian()) {
write(woff, value >>> 16); write(woff, value >>> 16);
write(woff + 1, value >>> 8 & 0xFF); write(woff + 1, value >>> 8 & 0xFF);
@ -1548,7 +1548,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeUnsignedMedium(int value) { public Buffer writeUnsignedMedium(int value) {
if (bigEndian()) { if (bigEndian()) {
write(value >>> 16); write(value >>> 16);
write(value >>> 8 & 0xFF); write(value >>> 8 & 0xFF);
@ -1562,7 +1562,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf setUnsignedMedium(int woff, int value) { public Buffer setUnsignedMedium(int woff, int value) {
if (bigEndian()) { if (bigEndian()) {
write(woff, value >>> 16); write(woff, value >>> 16);
write(woff + 1, value >>> 8 & 0xFF); write(woff + 1, value >>> 8 & 0xFF);
@ -1612,7 +1612,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeInt(int value) { public Buffer writeInt(int value) {
if (bigEndian()) { if (bigEndian()) {
write(value >>> 24); write(value >>> 24);
write(value >>> 16 & 0xFF); write(value >>> 16 & 0xFF);
@ -1628,7 +1628,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf setInt(int woff, int value) { public Buffer setInt(int woff, int value) {
if (bigEndian()) { if (bigEndian()) {
write(woff, value >>> 24); write(woff, value >>> 24);
write(woff + 1, value >>> 16 & 0xFF); write(woff + 1, value >>> 16 & 0xFF);
@ -1644,7 +1644,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeUnsignedInt(long value) { public Buffer writeUnsignedInt(long value) {
if (bigEndian()) { if (bigEndian()) {
write((int) (value >>> 24)); write((int) (value >>> 24));
write((int) (value >>> 16 & 0xFF)); write((int) (value >>> 16 & 0xFF));
@ -1660,7 +1660,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf setUnsignedInt(int woff, long value) { public Buffer setUnsignedInt(int woff, long value) {
if (bigEndian()) { if (bigEndian()) {
write(woff, (int) (value >>> 24)); write(woff, (int) (value >>> 24));
write(woff + 1, (int) (value >>> 16 & 0xFF)); write(woff + 1, (int) (value >>> 16 & 0xFF));
@ -1686,12 +1686,12 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeFloat(float value) { public Buffer writeFloat(float value) {
return writeUnsignedInt(Float.floatToRawIntBits(value)); return writeUnsignedInt(Float.floatToRawIntBits(value));
} }
@Override @Override
public Buf setFloat(int woff, float value) { public Buffer setFloat(int woff, float value) {
return setUnsignedInt(woff, Float.floatToRawIntBits(value)); return setUnsignedInt(woff, Float.floatToRawIntBits(value));
} }
@ -1718,7 +1718,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeLong(long value) { public Buffer writeLong(long value) {
if (bigEndian()) { if (bigEndian()) {
write((int) (value >>> 56)); write((int) (value >>> 56));
write((int) (value >>> 48 & 0xFF)); write((int) (value >>> 48 & 0xFF));
@ -1742,7 +1742,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf setLong(int woff, long value) { public Buffer setLong(int woff, long value) {
if (bigEndian()) { if (bigEndian()) {
write(woff, (int) (value >>> 56)); write(woff, (int) (value >>> 56));
write(woff + 1, (int) (value >>> 48 & 0xFF)); write(woff + 1, (int) (value >>> 48 & 0xFF));
@ -1776,12 +1776,12 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
} }
@Override @Override
public Buf writeDouble(double value) { public Buffer writeDouble(double value) {
return writeLong(Double.doubleToRawLongBits(value)); return writeLong(Double.doubleToRawLongBits(value));
} }
@Override @Override
public Buf setDouble(int woff, double value) { public Buffer setDouble(int woff, double value) {
return setLong(woff, Double.doubleToRawLongBits(value)); return setLong(woff, Double.doubleToRawLongBits(value));
} }

View File

@ -19,24 +19,24 @@ import java.lang.ref.Cleaner;
import static io.netty.buffer.api.Statics.NO_OP_DROP; import static io.netty.buffer.api.Statics.NO_OP_DROP;
class ManagedAllocator implements Allocator, AllocatorControl { class ManagedBufferAllocator implements BufferAllocator, AllocatorControl {
private final MemoryManager manager; private final MemoryManager manager;
private final Cleaner cleaner; private final Cleaner cleaner;
ManagedAllocator(MemoryManager manager, Cleaner cleaner) { ManagedBufferAllocator(MemoryManager manager, Cleaner cleaner) {
this.manager = manager; this.manager = manager;
this.cleaner = cleaner; this.cleaner = cleaner;
} }
@Override @Override
public Buf allocate(int size) { public Buffer allocate(int size) {
Allocator.checkSize(size); BufferAllocator.checkSize(size);
return manager.allocateShared(this, size, manager.drop(), cleaner); return manager.allocateShared(this, size, manager.drop(), cleaner);
} }
@Override @Override
public Object allocateUntethered(Buf originator, int size) { public Object allocateUntethered(Buffer originator, int size) {
Allocator.checkSize(size); BufferAllocator.checkSize(size);
var buf = manager.allocateShared(this, size, NO_OP_DROP, null); var buf = manager.allocateShared(this, size, NO_OP_DROP, null);
return manager.unwrapRecoverableMemory(buf); return manager.unwrapRecoverableMemory(buf);
} }

View File

@ -30,9 +30,9 @@ public interface MemoryManager {
} }
boolean isNative(); boolean isNative();
Buf allocateConfined(AllocatorControl alloc, long size, Drop<Buf> drop, Cleaner cleaner); Buffer allocateConfined(AllocatorControl alloc, long size, Drop<Buffer> drop, Cleaner cleaner);
Buf allocateShared(AllocatorControl allo, long size, Drop<Buf> drop, Cleaner cleaner); Buffer allocateShared(AllocatorControl allo, long size, Drop<Buffer> drop, Cleaner cleaner);
Drop<Buf> drop(); Drop<Buffer> drop();
Object unwrapRecoverableMemory(Buf buf); Object unwrapRecoverableMemory(Buffer buf);
Buf recoverMemory(Object recoverableMemory, Drop<Buf> drop); Buffer recoverMemory(Object recoverableMemory, Drop<Buffer> drop);
} }

View File

@ -24,11 +24,11 @@ import java.util.concurrent.ConcurrentLinkedQueue;
import static io.netty.buffer.api.Statics.NO_OP_DROP; import static io.netty.buffer.api.Statics.NO_OP_DROP;
import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodHandles.lookup;
class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> { class SizeClassedMemoryPool implements BufferAllocator, AllocatorControl, Drop<Buffer> {
private static final VarHandle CLOSE = Statics.findVarHandle( private static final VarHandle CLOSE = Statics.findVarHandle(
lookup(), SizeClassedMemoryPool.class, "closed", boolean.class); lookup(), SizeClassedMemoryPool.class, "closed", boolean.class);
private final MemoryManager manager; private final MemoryManager manager;
private final ConcurrentHashMap<Integer, ConcurrentLinkedQueue<Send<Buf>>> pool; private final ConcurrentHashMap<Integer, ConcurrentLinkedQueue<Send<Buffer>>> pool;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private volatile boolean closed; private volatile boolean closed;
@ -38,10 +38,10 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
} }
@Override @Override
public Buf allocate(int size) { public Buffer allocate(int size) {
Allocator.checkSize(size); BufferAllocator.checkSize(size);
var sizeClassPool = getSizeClassPool(size); var sizeClassPool = getSizeClassPool(size);
Send<Buf> send = sizeClassPool.poll(); Send<Buffer> send = sizeClassPool.poll();
if (send != null) { if (send != null) {
return send.receive() return send.receive()
.reset() .reset()
@ -56,13 +56,13 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
return manager; return manager;
} }
protected Buf createBuf(int size, Drop<Buf> drop) { protected Buffer createBuf(int size, Drop<Buffer> drop) {
var buf = manager.allocateShared(this, size, drop, null); var buf = manager.allocateShared(this, size, drop, null);
drop.attach(buf); drop.attach(buf);
return buf; return buf;
} }
protected Drop<Buf> getDrop() { protected Drop<Buffer> getDrop() {
return new CleanerPooledDrop(this, getMemoryManager(), this); return new CleanerPooledDrop(this, getMemoryManager(), this);
} }
@ -71,7 +71,7 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
if (CLOSE.compareAndSet(this, false, true)) { if (CLOSE.compareAndSet(this, false, true)) {
var capturedExceptions = new ArrayList<Exception>(4); var capturedExceptions = new ArrayList<Exception>(4);
pool.forEach((k, v) -> { pool.forEach((k, v) -> {
Send<Buf> send; Send<Buffer> send;
while ((send = v.poll()) != null) { while ((send = v.poll()) != null) {
try { try {
send.receive().close(); send.receive().close();
@ -89,7 +89,7 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
} }
@Override @Override
public void drop(Buf buf) { public void drop(Buffer buf) {
if (closed) { if (closed) {
dispose(buf); dispose(buf);
return; return;
@ -97,7 +97,7 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
var sizeClassPool = getSizeClassPool(buf.capacity()); var sizeClassPool = getSizeClassPool(buf.capacity());
sizeClassPool.offer(buf.send()); sizeClassPool.offer(buf.send());
if (closed) { if (closed) {
Send<Buf> send; Send<Buffer> send;
while ((send = sizeClassPool.poll()) != null) { while ((send = sizeClassPool.poll()) != null) {
send.receive().close(); send.receive().close();
} }
@ -105,12 +105,12 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
} }
@Override @Override
public Object allocateUntethered(Buf originator, int size) { public Object allocateUntethered(Buffer originator, int size) {
var sizeClassPool = getSizeClassPool(size); var sizeClassPool = getSizeClassPool(size);
Send<Buf> send = sizeClassPool.poll(); Send<Buffer> send = sizeClassPool.poll();
Buf untetheredBuf; Buffer untetheredBuf;
if (send != null) { if (send != null) {
var transfer = (TransferSend<Buf, Buf>) send; var transfer = (TransferSend<Buffer, Buffer>) send;
var owned = transfer.unsafeUnwrapOwned(); var owned = transfer.unsafeUnwrapOwned();
untetheredBuf = owned.transferOwnership(NO_OP_DROP); untetheredBuf = owned.transferOwnership(NO_OP_DROP);
} else { } else {
@ -127,11 +127,11 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
buf.close(); buf.close();
} }
private ConcurrentLinkedQueue<Send<Buf>> getSizeClassPool(int size) { private ConcurrentLinkedQueue<Send<Buffer>> getSizeClassPool(int size) {
return pool.computeIfAbsent(size, k -> new ConcurrentLinkedQueue<>()); return pool.computeIfAbsent(size, k -> new ConcurrentLinkedQueue<>());
} }
private void dispose(Buf buf) { private void dispose(Buffer buf) {
manager.drop().drop(buf); manager.drop().drop(buf);
} }
} }

View File

@ -21,7 +21,7 @@ import java.lang.ref.Cleaner;
interface Statics { interface Statics {
Cleaner CLEANER = Cleaner.create(); Cleaner CLEANER = Cleaner.create();
Drop<Buf> NO_OP_DROP = buf -> { Drop<Buffer> NO_OP_DROP = buf -> {
}; };
static VarHandle findVarHandle(Lookup lookup, Class<?> recv, String name, Class<?> type) { static VarHandle findVarHandle(Lookup lookup, Class<?> recv, String name, Class<?> type) {

View File

@ -16,10 +16,10 @@
package io.netty.buffer.api.memseg; package io.netty.buffer.api.memseg;
import io.netty.buffer.api.AllocatorControl; import io.netty.buffer.api.AllocatorControl;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import io.netty.buffer.api.Drop; import io.netty.buffer.api.Drop;
import io.netty.buffer.api.MemoryManager; import io.netty.buffer.api.MemoryManager;
import io.netty.buffer.api.memseg.MemSegBuf.RecoverableMemory; import io.netty.buffer.api.memseg.MemSegBuffer.RecoverableMemory;
import jdk.incubator.foreign.MemorySegment; import jdk.incubator.foreign.MemorySegment;
import java.lang.ref.Cleaner; import java.lang.ref.Cleaner;
@ -29,38 +29,38 @@ public abstract class AbstractMemorySegmentManager implements MemoryManager {
public abstract boolean isNative(); public abstract boolean isNative();
@Override @Override
public Buf allocateConfined(AllocatorControl alloc, long size, Drop<Buf> drop, Cleaner cleaner) { public Buffer allocateConfined(AllocatorControl alloc, long size, Drop<Buffer> drop, Cleaner cleaner) {
var segment = createSegment(size); var segment = createSegment(size);
if (cleaner != null) { if (cleaner != null) {
segment = segment.registerCleaner(cleaner); segment = segment.registerCleaner(cleaner);
} }
return new MemSegBuf(segment, convert(drop), alloc); return new MemSegBuffer(segment, convert(drop), alloc);
} }
@Override @Override
public Buf allocateShared(AllocatorControl alloc, long size, Drop<Buf> drop, Cleaner cleaner) { public Buffer allocateShared(AllocatorControl alloc, long size, Drop<Buffer> drop, Cleaner cleaner) {
var segment = createSegment(size).share(); var segment = createSegment(size).share();
if (cleaner != null) { if (cleaner != null) {
segment = segment.registerCleaner(cleaner); segment = segment.registerCleaner(cleaner);
} }
return new MemSegBuf(segment, convert(drop), alloc); return new MemSegBuffer(segment, convert(drop), alloc);
} }
protected abstract MemorySegment createSegment(long size); protected abstract MemorySegment createSegment(long size);
@Override @Override
public Drop<Buf> drop() { public Drop<Buffer> drop() {
return convert(MemSegBuf.SEGMENT_CLOSE); return convert(MemSegBuffer.SEGMENT_CLOSE);
} }
@Override @Override
public Object unwrapRecoverableMemory(Buf buf) { public Object unwrapRecoverableMemory(Buffer buf) {
var b = (MemSegBuf) buf; var b = (MemSegBuffer) buf;
return b.recoverableMemory(); return b.recoverableMemory();
} }
@Override @Override
public Buf recoverMemory(Object recoverableMemory, Drop<Buf> drop) { public Buffer recoverMemory(Object recoverableMemory, Drop<Buffer> drop) {
var recovery = (RecoverableMemory) recoverableMemory; var recovery = (RecoverableMemory) recoverableMemory;
return recovery.recover(convert(drop)); return recovery.recover(convert(drop));
} }

View File

@ -20,7 +20,7 @@ import io.netty.buffer.api.Drop;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle; import java.lang.invoke.VarHandle;
class BifurcatedDrop implements Drop<MemSegBuf> { class BifurcatedDrop implements Drop<MemSegBuffer> {
private static final VarHandle COUNT; private static final VarHandle COUNT;
static { static {
try { try {
@ -30,12 +30,12 @@ class BifurcatedDrop implements Drop<MemSegBuf> {
} }
} }
private final MemSegBuf originalBuf; private final MemSegBuffer originalBuf;
private final Drop<MemSegBuf> delegate; private final Drop<MemSegBuffer> delegate;
@SuppressWarnings("FieldMayBeFinal") @SuppressWarnings("FieldMayBeFinal")
private volatile int count; private volatile int count;
BifurcatedDrop(MemSegBuf originalBuf, Drop<MemSegBuf> delegate) { BifurcatedDrop(MemSegBuffer originalBuf, Drop<MemSegBuffer> delegate) {
this.originalBuf = originalBuf; this.originalBuf = originalBuf;
this.delegate = delegate; this.delegate = delegate;
count = 2; // These are created by buffer bifurcation, so we initially have 2 references to this drop. count = 2; // These are created by buffer bifurcation, so we initially have 2 references to this drop.
@ -50,7 +50,7 @@ class BifurcatedDrop implements Drop<MemSegBuf> {
} }
@Override @Override
public void drop(MemSegBuf buf) { public void drop(MemSegBuffer buf) {
int c; int c;
int n; int n;
do { do {
@ -66,11 +66,11 @@ class BifurcatedDrop implements Drop<MemSegBuf> {
} }
@Override @Override
public void attach(MemSegBuf obj) { public void attach(MemSegBuffer obj) {
delegate.attach(obj); delegate.attach(obj);
} }
Drop<MemSegBuf> unwrap() { Drop<MemSegBuffer> unwrap() {
return delegate; return delegate;
} }

View File

@ -15,7 +15,7 @@
*/ */
package io.netty.buffer.api.memseg; package io.netty.buffer.api.memseg;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import io.netty.buffer.api.Drop; import io.netty.buffer.api.Drop;
import jdk.incubator.foreign.MemorySegment; import jdk.incubator.foreign.MemorySegment;
@ -31,13 +31,13 @@ public class HeapMemorySegmentManager extends AbstractMemorySegmentManager {
} }
@Override @Override
public Drop<Buf> drop() { public Drop<Buffer> drop() {
return convert(buf -> buf.makeInaccessible()); return convert(buf -> buf.makeInaccessible());
} }
@SuppressWarnings({ "unchecked", "UnnecessaryLocalVariable" }) @SuppressWarnings({ "unchecked", "UnnecessaryLocalVariable" })
private static Drop<Buf> convert(Drop<MemSegBuf> drop) { private static Drop<Buffer> convert(Drop<MemSegBuffer> drop) {
Drop<?> tmp = drop; Drop<?> tmp = drop;
return (Drop<Buf>) tmp; return (Drop<Buffer>) tmp;
} }
} }

View File

@ -15,9 +15,9 @@
*/ */
package io.netty.buffer.api.memseg; package io.netty.buffer.api.memseg;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.AllocatorControl; import io.netty.buffer.api.AllocatorControl;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import io.netty.buffer.api.ByteCursor; import io.netty.buffer.api.ByteCursor;
import io.netty.buffer.api.ComponentProcessor.ReadableComponent; import io.netty.buffer.api.ComponentProcessor.ReadableComponent;
import io.netty.buffer.api.ComponentProcessor.ReadableComponentProcessor; import io.netty.buffer.api.ComponentProcessor.ReadableComponentProcessor;
@ -46,9 +46,9 @@ import static jdk.incubator.foreign.MemoryAccess.setIntAtOffset;
import static jdk.incubator.foreign.MemoryAccess.setLongAtOffset; import static jdk.incubator.foreign.MemoryAccess.setLongAtOffset;
import static jdk.incubator.foreign.MemoryAccess.setShortAtOffset; import static jdk.incubator.foreign.MemoryAccess.setShortAtOffset;
class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableComponent, WritableComponent { class MemSegBuffer extends RcSupport<Buffer, MemSegBuffer> implements Buffer, ReadableComponent, WritableComponent {
private static final MemorySegment CLOSED_SEGMENT; private static final MemorySegment CLOSED_SEGMENT;
static final Drop<MemSegBuf> SEGMENT_CLOSE; static final Drop<MemSegBuffer> SEGMENT_CLOSE;
static { static {
CLOSED_SEGMENT = MemorySegment.ofArray(new byte[0]); CLOSED_SEGMENT = MemorySegment.ofArray(new byte[0]);
@ -68,11 +68,11 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
private int roff; private int roff;
private int woff; private int woff;
MemSegBuf(MemorySegment segmet, Drop<MemSegBuf> drop, AllocatorControl alloc) { MemSegBuffer(MemorySegment segmet, Drop<MemSegBuffer> drop, AllocatorControl alloc) {
this(segmet, drop, alloc, true); this(segmet, drop, alloc, true);
} }
private MemSegBuf(MemorySegment segment, Drop<MemSegBuf> drop, AllocatorControl alloc, boolean isSendable) { private MemSegBuffer(MemorySegment segment, Drop<MemSegBuffer> drop, AllocatorControl alloc, boolean isSendable) {
super(drop); super(drop);
this.alloc = alloc; this.alloc = alloc;
seg = segment; seg = segment;
@ -83,11 +83,11 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
@Override @Override
public String toString() { public String toString() {
return "Buf[roff:" + roff + ", woff:" + woff + ", cap:" + seg.byteSize() + ']'; return "Buffer[roff:" + roff + ", woff:" + woff + ", cap:" + seg.byteSize() + ']';
} }
@Override @Override
public Buf order(ByteOrder order) { public Buffer order(ByteOrder order) {
this.order = order; this.order = order;
return this; return this;
} }
@ -108,7 +108,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public MemSegBuf readerOffset(int index) { public MemSegBuffer readerOffset(int index) {
checkRead(index, 0); checkRead(index, 0);
roff = index; roff = index;
return this; return this;
@ -120,14 +120,14 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public MemSegBuf writerOffset(int index) { public MemSegBuffer writerOffset(int index) {
checkWrite(index, 0); checkWrite(index, 0);
woff = index; woff = index;
return this; return this;
} }
@Override @Override
public Buf fill(byte value) { public Buffer fill(byte value) {
checkWrite(0, capacity()); checkWrite(0, capacity());
seg.fill(value); seg.fill(value);
return this; return this;
@ -213,7 +213,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf readOnly(boolean readOnly) { public Buffer readOnly(boolean readOnly) {
wseg = readOnly? CLOSED_SEGMENT : seg; wseg = readOnly? CLOSED_SEGMENT : seg;
return this; return this;
} }
@ -224,18 +224,18 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf slice(int offset, int length) { public Buffer slice(int offset, int length) {
if (length < 0) { if (length < 0) {
throw new IllegalArgumentException("Length cannot be negative: " + length + '.'); throw new IllegalArgumentException("Length cannot be negative: " + length + '.');
} }
var slice = seg.asSlice(offset, length); var slice = seg.asSlice(offset, length);
acquire(); acquire();
Drop<MemSegBuf> drop = b -> { Drop<MemSegBuffer> drop = b -> {
close(); close();
b.makeInaccessible(); b.makeInaccessible();
}; };
var sendable = false; // Sending implies ownership change, which we can't do for slices. var sendable = false; // Sending implies ownership change, which we can't do for slices.
return new MemSegBuf(slice, drop, alloc, sendable) return new MemSegBuffer(slice, drop, alloc, sendable)
.writerOffset(length) .writerOffset(length)
.order(order()) .order(order())
.readOnly(readOnly()); .readOnly(readOnly());
@ -273,9 +273,9 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public void copyInto(int srcPos, Buf dest, int destPos, int length) { public void copyInto(int srcPos, Buffer dest, int destPos, int length) {
if (dest instanceof MemSegBuf) { if (dest instanceof MemSegBuffer) {
var memSegBuf = (MemSegBuf) dest; var memSegBuf = (MemSegBuffer) dest;
memSegBuf.checkWrite(destPos, length); memSegBuf.checkWrite(destPos, length);
copyInto(srcPos, memSegBuf.seg, destPos, length); copyInto(srcPos, memSegBuf.seg, destPos, length);
return; return;
@ -456,7 +456,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
// Allocate a bigger buffer. // Allocate a bigger buffer.
long newSize = capacity() + size - (long) writableBytes(); long newSize = capacity() + size - (long) writableBytes();
Allocator.checkSize(newSize); BufferAllocator.checkSize(newSize);
RecoverableMemory recoverableMemory = (RecoverableMemory) alloc.allocateUntethered(this, (int) newSize); RecoverableMemory recoverableMemory = (RecoverableMemory) alloc.allocateUntethered(this, (int) newSize);
var newSegment = recoverableMemory.segment; var newSegment = recoverableMemory.segment;
@ -484,7 +484,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf bifurcate() { public Buffer bifurcate() {
if (!isOwned()) { if (!isOwned()) {
throw new IllegalStateException("Cannot bifurcate a buffer that is not owned."); throw new IllegalStateException("Cannot bifurcate a buffer that is not owned.");
} }
@ -496,11 +496,11 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
if (drop instanceof BifurcatedDrop) { if (drop instanceof BifurcatedDrop) {
((BifurcatedDrop) drop).increment(); ((BifurcatedDrop) drop).increment();
} else { } else {
drop = new BifurcatedDrop(new MemSegBuf(seg, drop, alloc), drop); drop = new BifurcatedDrop(new MemSegBuffer(seg, drop, alloc), drop);
unsafeSetDrop(drop); unsafeSetDrop(drop);
} }
var bifurcatedSeg = seg.asSlice(0, woff); var bifurcatedSeg = seg.asSlice(0, woff);
var bifurcatedBuf = new MemSegBuf(bifurcatedSeg, drop, alloc); var bifurcatedBuf = new MemSegBuffer(bifurcatedSeg, drop, alloc);
bifurcatedBuf.woff = woff; bifurcatedBuf.woff = woff;
bifurcatedBuf.roff = roff; bifurcatedBuf.roff = roff;
bifurcatedBuf.order(order); bifurcatedBuf.order(order);
@ -591,7 +591,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeByte(byte value) { public Buffer writeByte(byte value) {
try { try {
setByteAtOffset(wseg, woff, value); setByteAtOffset(wseg, woff, value);
woff += Byte.BYTES; woff += Byte.BYTES;
@ -602,7 +602,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setByte(int woff, byte value) { public Buffer setByte(int woff, byte value) {
try { try {
setByteAtOffset(wseg, woff, value); setByteAtOffset(wseg, woff, value);
return this; return this;
@ -612,7 +612,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeUnsignedByte(int value) { public Buffer writeUnsignedByte(int value) {
try { try {
setByteAtOffset(wseg, woff, (byte) (value & 0xFF)); setByteAtOffset(wseg, woff, (byte) (value & 0xFF));
woff += Byte.BYTES; woff += Byte.BYTES;
@ -623,7 +623,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setUnsignedByte(int woff, int value) { public Buffer setUnsignedByte(int woff, int value) {
try { try {
setByteAtOffset(wseg, woff, (byte) (value & 0xFF)); setByteAtOffset(wseg, woff, (byte) (value & 0xFF));
return this; return this;
@ -647,7 +647,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeChar(char value) { public Buffer writeChar(char value) {
try { try {
setCharAtOffset(wseg, woff, order, value); setCharAtOffset(wseg, woff, order, value);
woff += 2; woff += 2;
@ -658,7 +658,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setChar(int woff, char value) { public Buffer setChar(int woff, char value) {
try { try {
setCharAtOffset(wseg, woff, order, value); setCharAtOffset(wseg, woff, order, value);
return this; return this;
@ -696,7 +696,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeShort(short value) { public Buffer writeShort(short value) {
try { try {
setShortAtOffset(wseg, woff, order, value); setShortAtOffset(wseg, woff, order, value);
woff += Short.BYTES; woff += Short.BYTES;
@ -707,7 +707,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setShort(int woff, short value) { public Buffer setShort(int woff, short value) {
try { try {
setShortAtOffset(wseg, woff, order, value); setShortAtOffset(wseg, woff, order, value);
return this; return this;
@ -717,7 +717,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeUnsignedShort(int value) { public Buffer writeUnsignedShort(int value) {
try { try {
setShortAtOffset(wseg, woff, order, (short) (value & 0xFFFF)); setShortAtOffset(wseg, woff, order, (short) (value & 0xFFFF));
woff += Short.BYTES; woff += Short.BYTES;
@ -728,7 +728,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setUnsignedShort(int woff, int value) { public Buffer setUnsignedShort(int woff, int value) {
try { try {
setShortAtOffset(wseg, woff, order, (short) (value & 0xFFFF)); setShortAtOffset(wseg, woff, order, (short) (value & 0xFFFF));
return this; return this;
@ -790,7 +790,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeMedium(int value) { public Buffer writeMedium(int value) {
checkWrite(woff, 3); checkWrite(woff, 3);
if (order == ByteOrder.BIG_ENDIAN) { if (order == ByteOrder.BIG_ENDIAN) {
setByteAtOffset(wseg, woff, (byte) (value >> 16)); setByteAtOffset(wseg, woff, (byte) (value >> 16));
@ -806,7 +806,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setMedium(int woff, int value) { public Buffer setMedium(int woff, int value) {
checkWrite(woff, 3); checkWrite(woff, 3);
if (order == ByteOrder.BIG_ENDIAN) { if (order == ByteOrder.BIG_ENDIAN) {
setByteAtOffset(wseg, woff, (byte) (value >> 16)); setByteAtOffset(wseg, woff, (byte) (value >> 16));
@ -821,7 +821,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeUnsignedMedium(int value) { public Buffer writeUnsignedMedium(int value) {
checkWrite(woff, 3); checkWrite(woff, 3);
if (order == ByteOrder.BIG_ENDIAN) { if (order == ByteOrder.BIG_ENDIAN) {
setByteAtOffset(wseg, woff, (byte) (value >> 16)); setByteAtOffset(wseg, woff, (byte) (value >> 16));
@ -837,7 +837,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setUnsignedMedium(int woff, int value) { public Buffer setUnsignedMedium(int woff, int value) {
checkWrite(woff, 3); checkWrite(woff, 3);
if (order == ByteOrder.BIG_ENDIAN) { if (order == ByteOrder.BIG_ENDIAN) {
setByteAtOffset(wseg, woff, (byte) (value >> 16)); setByteAtOffset(wseg, woff, (byte) (value >> 16));
@ -880,7 +880,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeInt(int value) { public Buffer writeInt(int value) {
try { try {
setIntAtOffset(wseg, woff, order, value); setIntAtOffset(wseg, woff, order, value);
woff += Integer.BYTES; woff += Integer.BYTES;
@ -891,7 +891,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setInt(int woff, int value) { public Buffer setInt(int woff, int value) {
try { try {
setIntAtOffset(wseg, woff, order, value); setIntAtOffset(wseg, woff, order, value);
return this; return this;
@ -901,7 +901,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeUnsignedInt(long value) { public Buffer writeUnsignedInt(long value) {
try { try {
setIntAtOffset(wseg, woff, order, (int) (value & 0xFFFFFFFFL)); setIntAtOffset(wseg, woff, order, (int) (value & 0xFFFFFFFFL));
woff += Integer.BYTES; woff += Integer.BYTES;
@ -912,7 +912,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setUnsignedInt(int woff, long value) { public Buffer setUnsignedInt(int woff, long value) {
try { try {
setIntAtOffset(wseg, woff, order, (int) (value & 0xFFFFFFFFL)); setIntAtOffset(wseg, woff, order, (int) (value & 0xFFFFFFFFL));
return this; return this;
@ -936,7 +936,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeFloat(float value) { public Buffer writeFloat(float value) {
try { try {
setFloatAtOffset(wseg, woff, order, value); setFloatAtOffset(wseg, woff, order, value);
woff += Float.BYTES; woff += Float.BYTES;
@ -947,7 +947,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setFloat(int woff, float value) { public Buffer setFloat(int woff, float value) {
try { try {
setFloatAtOffset(wseg, woff, order, value); setFloatAtOffset(wseg, woff, order, value);
return this; return this;
@ -971,7 +971,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeLong(long value) { public Buffer writeLong(long value) {
try { try {
setLongAtOffset(wseg, woff, order, value); setLongAtOffset(wseg, woff, order, value);
woff += Long.BYTES; woff += Long.BYTES;
@ -982,7 +982,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setLong(int woff, long value) { public Buffer setLong(int woff, long value) {
try { try {
setLongAtOffset(wseg, woff, order, value); setLongAtOffset(wseg, woff, order, value);
return this; return this;
@ -1006,7 +1006,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf writeDouble(double value) { public Buffer writeDouble(double value) {
try { try {
setDoubleAtOffset(wseg, woff, order, value); setDoubleAtOffset(wseg, woff, order, value);
woff += Double.BYTES; woff += Double.BYTES;
@ -1017,7 +1017,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
} }
@Override @Override
public Buf setDouble(int woff, double value) { public Buffer setDouble(int woff, double value) {
try { try {
setDoubleAtOffset(wseg, woff, order, value); setDoubleAtOffset(wseg, woff, order, value);
return this; return this;
@ -1028,7 +1028,7 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
// </editor-fold> // </editor-fold>
@Override @Override
protected Owned<MemSegBuf> prepareSend() { protected Owned<MemSegBuffer> prepareSend() {
var order = this.order; var order = this.order;
var roff = this.roff; var roff = this.roff;
var woff = this.woff; var woff = this.woff;
@ -1036,10 +1036,10 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
boolean isConfined = seg.ownerThread() == null; boolean isConfined = seg.ownerThread() == null;
MemorySegment transferSegment = isConfined? seg : seg.share(); MemorySegment transferSegment = isConfined? seg : seg.share();
makeInaccessible(); makeInaccessible();
return new Owned<MemSegBuf>() { return new Owned<MemSegBuffer>() {
@Override @Override
public MemSegBuf transferOwnership(Drop<MemSegBuf> drop) { public MemSegBuffer transferOwnership(Drop<MemSegBuffer> drop) {
MemSegBuf copy = new MemSegBuf(transferSegment, drop, alloc); MemSegBuffer copy = new MemSegBuffer(transferSegment, drop, alloc);
copy.order = order; copy.order = order;
copy.roff = roff; copy.roff = roff;
copy.woff = woff; copy.woff = woff;
@ -1136,8 +1136,8 @@ class MemSegBuf extends RcSupport<Buf, MemSegBuf> implements Buf, ReadableCompon
this.alloc = alloc; this.alloc = alloc;
} }
Buf recover(Drop<MemSegBuf> drop) { Buffer recover(Drop<MemSegBuffer> drop) {
return new MemSegBuf(segment, drop, alloc); return new MemSegBuffer(segment, drop, alloc);
} }
} }
} }

View File

@ -15,6 +15,6 @@
*/ */
/** /**
* Experimental {@code Buf} implementation, based on the MemorySegment API from OpenJDK Panama Foreign. * Experimental {@code Buffer} implementation, based on the MemorySegment API from OpenJDK Panama Foreign.
*/ */
package io.netty.buffer.api.memseg; package io.netty.buffer.api.memseg;

View File

@ -15,6 +15,6 @@
*/ */
/** /**
* Incubating {@code Buf} API, as a proposed alternative to {@code ByteBuf}. * Incubating {@code Buffer} API, as a proposed alternative to {@code ByteBuf}.
*/ */
package io.netty.buffer.api; package io.netty.buffer.api;

View File

@ -20,13 +20,13 @@ import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
class BufRefTest { class BufferRefTest {
@Test @Test
public void closingBufRefMustCloseOwnedBuf() { public void closingBufRefMustCloseOwnedBuf() {
try (Allocator allocator = Allocator.heap()) { try (BufferAllocator allocator = BufferAllocator.heap()) {
BufRef ref; BufferRef ref;
try (Buf b = allocator.allocate(8)) { try (Buffer b = allocator.allocate(8)) {
ref = new BufRef(b); ref = new BufferRef(b);
} }
ref.contents().writeInt(42); ref.contents().writeInt(42);
assertThat(ref.contents().readInt()).isEqualTo(42); assertThat(ref.contents().readInt()).isEqualTo(42);
@ -37,9 +37,9 @@ class BufRefTest {
@Test @Test
public void closingBufRefMustCloseOwnedBufFromSend() { public void closingBufRefMustCloseOwnedBufFromSend() {
try (Allocator allocator = Allocator.heap(); try (BufferAllocator allocator = BufferAllocator.heap();
Buf buf = allocator.allocate(8)) { Buffer buf = allocator.allocate(8)) {
BufRef ref = new BufRef(buf.send()); BufferRef ref = new BufferRef(buf.send());
ref.contents().writeInt(42); ref.contents().writeInt(42);
assertThat(ref.contents().readInt()).isEqualTo(42); assertThat(ref.contents().readInt()).isEqualTo(42);
ref.close(); ref.close();
@ -49,17 +49,17 @@ class BufRefTest {
@Test @Test
public void mustCloseOwnedBufferWhenReplaced() { public void mustCloseOwnedBufferWhenReplaced() {
try (Allocator allocator = Allocator.heap()) { try (BufferAllocator allocator = BufferAllocator.heap()) {
Buf orig; Buffer orig;
BufRef ref; BufferRef ref;
try (Buf buf = allocator.allocate(8)) { try (Buffer buf = allocator.allocate(8)) {
ref = new BufRef(orig = buf); ref = new BufferRef(orig = buf);
} }
orig.writeInt(42); orig.writeInt(42);
assertThat(ref.contents().readInt()).isEqualTo(42); assertThat(ref.contents().readInt()).isEqualTo(42);
try (Buf buf = allocator.allocate(8)) { try (Buffer buf = allocator.allocate(8)) {
ref.replace(buf); // Pass replacement directly. ref.replace(buf); // Pass replacement directly.
} }
@ -73,17 +73,17 @@ class BufRefTest {
@Test @Test
public void mustCloseOwnedBufferWhenReplacedFromSend() { public void mustCloseOwnedBufferWhenReplacedFromSend() {
try (Allocator allocator = Allocator.heap()) { try (BufferAllocator allocator = BufferAllocator.heap()) {
Buf orig; Buffer orig;
BufRef ref; BufferRef ref;
try (Buf buf = allocator.allocate(8)) { try (Buffer buf = allocator.allocate(8)) {
ref = new BufRef(orig = buf); ref = new BufferRef(orig = buf);
} }
orig.writeInt(42); orig.writeInt(42);
assertThat(ref.contents().readInt()).isEqualTo(42); assertThat(ref.contents().readInt()).isEqualTo(42);
try (Buf buf = allocator.allocate(8)) { try (Buffer buf = allocator.allocate(8)) {
ref.replace(buf.send()); // Pass replacement via send(). ref.replace(buf.send()); // Pass replacement via send().
} }
@ -97,12 +97,12 @@ class BufRefTest {
@Test @Test
public void sendingRefMustSendBuffer() { public void sendingRefMustSendBuffer() {
try (Allocator allocator = Allocator.heap(); try (BufferAllocator allocator = BufferAllocator.heap();
BufRef refA = new BufRef(allocator.allocate(8).send())) { BufferRef refA = new BufferRef(allocator.allocate(8).send())) {
refA.contents().writeInt(42); refA.contents().writeInt(42);
Send<BufRef> send = refA.send(); Send<BufferRef> send = refA.send();
assertThrows(IllegalStateException.class, () -> refA.contents().readInt()); assertThrows(IllegalStateException.class, () -> refA.contents().readInt());
try (BufRef refB = send.receive()) { try (BufferRef refB = send.receive()) {
assertThat(refB.contents().readInt()).isEqualTo(42); assertThat(refB.contents().readInt()).isEqualTo(42);
} }
} }

View File

@ -19,23 +19,23 @@ import java.util.Arrays;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.function.Supplier; import java.util.function.Supplier;
public final class Fixture implements Supplier<Allocator> { public final class Fixture implements Supplier<BufferAllocator> {
private final String name; private final String name;
private final Supplier<Allocator> factory; private final Supplier<BufferAllocator> factory;
private final EnumSet<Properties> properties; private final EnumSet<Properties> properties;
public Fixture(String name, Supplier<Allocator> factory, Properties... props) { public Fixture(String name, Supplier<BufferAllocator> factory, Properties... props) {
this.name = name; this.name = name;
this.factory = factory; this.factory = factory;
properties = EnumSet.copyOf(Arrays.asList(props)); properties = EnumSet.copyOf(Arrays.asList(props));
} }
public Allocator createAllocator() { public BufferAllocator createAllocator() {
return factory.get(); return factory.get();
} }
@Override @Override
public Allocator get() { public BufferAllocator get() {
return factory.get(); return factory.get();
} }

View File

@ -15,8 +15,8 @@
*/ */
package io.netty.buffer.api.benchmarks; package io.netty.buffer.api.benchmarks;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Fork;
@ -44,29 +44,29 @@ public class ByteIterationBenchmark {
@Param({"heap", "direct", "composite-heap", "composite-direct"}) @Param({"heap", "direct", "composite-heap", "composite-direct"})
public String type; public String type;
Allocator allocator; BufferAllocator allocator;
private Buf buf; private Buffer buf;
@Setup @Setup
public void setUp() { public void setUp() {
switch (type) { switch (type) {
case "heap": case "heap":
allocator = Allocator.heap(); allocator = BufferAllocator.heap();
buf = allocator.allocate(SIZE); buf = allocator.allocate(SIZE);
break; break;
case "direct": case "direct":
allocator = Allocator.direct(); allocator = BufferAllocator.direct();
buf = allocator.allocate(SIZE); buf = allocator.allocate(SIZE);
break; break;
case "composite-heap": case "composite-heap":
allocator = Allocator.heap(); allocator = BufferAllocator.heap();
try (var a = allocator.allocate(SIZE / 2); try (var a = allocator.allocate(SIZE / 2);
var b = allocator.allocate(SIZE / 2)) { var b = allocator.allocate(SIZE / 2)) {
buf = allocator.compose(a, b); buf = allocator.compose(a, b);
} }
break; break;
case "composite-direct": case "composite-direct":
allocator = Allocator.direct(); allocator = BufferAllocator.direct();
try (var a = allocator.allocate(SIZE / 2); try (var a = allocator.allocate(SIZE / 2);
var b = allocator.allocate(SIZE / 2)) { var b = allocator.allocate(SIZE / 2)) {
buf = allocator.compose(a, b); buf = allocator.compose(a, b);

View File

@ -15,8 +15,8 @@
*/ */
package io.netty.buffer.api.benchmarks; package io.netty.buffer.api.benchmarks;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Fork;
@ -42,30 +42,30 @@ public class MemSegBufAccessBenchmark {
public enum BBufType { public enum BBufType {
DIRECT { DIRECT {
@Override @Override
Buf newBuffer() { Buffer newBuffer() {
return Allocator.direct().allocate(64); return BufferAllocator.direct().allocate(64);
} }
}, },
HEAP { HEAP {
@Override @Override
Buf newBuffer() { Buffer newBuffer() {
return Allocator.heap().allocate(64); return BufferAllocator.heap().allocate(64);
} }
}, },
// COMPOSITE { // COMPOSITE {
// @Override // @Override
// Buf newBuffer() { // Buffer newBuffer() {
// return Unpooled.wrappedBuffer(UNSAFE.newBuffer(), HEAP.newBuffer()); // return Unpooled.wrappedBuffer(UNSAFE.newBuffer(), HEAP.newBuffer());
// } // }
// }, // },
// NIO { // NIO {
// @Override // @Override
// Buf newBuffer() { // Buffer newBuffer() {
// return new NioFacade(BBuffer.allocateDirect(64)); // return new NioFacade(BBuffer.allocateDirect(64));
// } // }
// } // }
; ;
abstract Buf newBuffer(); abstract Buffer newBuffer();
} }
@Param @Param
@ -80,7 +80,7 @@ public class MemSegBufAccessBenchmark {
buffer.writerOffset(batchSize); buffer.writerOffset(batchSize);
} }
private Buf buffer; private Buffer buffer;
@TearDown @TearDown
public void tearDown() { public void tearDown() {
@ -93,7 +93,7 @@ public class MemSegBufAccessBenchmark {
} }
@Benchmark @Benchmark
public Buf setLong() { public Buffer setLong() {
return buffer.setLong(0, 1); return buffer.setLong(0, 1);
} }

View File

@ -15,8 +15,8 @@
*/ */
package io.netty.buffer.api.benchmarks; package io.netty.buffer.api.benchmarks;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Fork;
@ -41,10 +41,10 @@ import static java.util.concurrent.CompletableFuture.completedFuture;
@OutputTimeUnit(TimeUnit.MICROSECONDS) @OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark) @State(Scope.Benchmark)
public class MemorySegmentClosedByCleanerBenchmark { public class MemorySegmentClosedByCleanerBenchmark {
private static final Allocator heap = Allocator.heap(); private static final BufferAllocator heap = BufferAllocator.heap();
private static final Allocator heapPooled = Allocator.pooledHeap(); private static final BufferAllocator heapPooled = BufferAllocator.pooledHeap();
private static final Allocator direct = Allocator.direct(); private static final BufferAllocator direct = BufferAllocator.direct();
private static final Allocator directPooled = Allocator.pooledDirect(); private static final BufferAllocator directPooled = BufferAllocator.pooledDirect();
@Param({"heavy", "light"}) @Param({"heavy", "light"})
public String workload; public String workload;
@ -62,56 +62,56 @@ public class MemorySegmentClosedByCleanerBenchmark {
} }
@Benchmark @Benchmark
public Buf explicitCloseHeap() throws Exception { public Buffer explicitCloseHeap() throws Exception {
try (Buf buf = process(heap.allocate(256))) { try (Buffer buf = process(heap.allocate(256))) {
return buf; return buf;
} }
} }
@Benchmark @Benchmark
public Buf explicitPooledCloseHeap() throws Exception { public Buffer explicitPooledCloseHeap() throws Exception {
try (Buf buf = process(heapPooled.allocate(256))) { try (Buffer buf = process(heapPooled.allocate(256))) {
return buf; return buf;
} }
} }
@Benchmark @Benchmark
public Buf explicitCloseDirect() throws Exception { public Buffer explicitCloseDirect() throws Exception {
try (Buf buf = process(direct.allocate(256))) { try (Buffer buf = process(direct.allocate(256))) {
return buf; return buf;
} }
} }
@Benchmark @Benchmark
public Buf explicitPooledCloseDirect() throws Exception { public Buffer explicitPooledCloseDirect() throws Exception {
try (Buf buf = process(directPooled.allocate(256))) { try (Buffer buf = process(directPooled.allocate(256))) {
return buf; return buf;
} }
} }
@Benchmark @Benchmark
public Buf cleanerClose() throws Exception { public Buffer cleanerClose() throws Exception {
return process(direct.allocate(256)); return process(direct.allocate(256));
} }
@Benchmark @Benchmark
public Buf cleanerClosePooled() throws Exception { public Buffer cleanerClosePooled() throws Exception {
return process(directPooled.allocate(256)); return process(directPooled.allocate(256));
} }
private Buf process(Buf buffer) throws Exception { private Buffer process(Buffer buffer) throws Exception {
// Simulate some async network server thingy, processing the buffer. // Simulate some async network server thingy, processing the buffer.
var tlr = ThreadLocalRandom.current(); var tlr = ThreadLocalRandom.current();
if (isHeavy) { if (isHeavy) {
return completedFuture(buffer.send()).thenApplyAsync(send -> { return completedFuture(buffer.send()).thenApplyAsync(send -> {
try (Buf buf = send.receive()) { try (Buffer buf = send.receive()) {
while (buf.writableBytes() > 0) { while (buf.writableBytes() > 0) {
buf.writeByte((byte) tlr.nextInt()); buf.writeByte((byte) tlr.nextInt());
} }
return buf.send(); return buf.send();
} }
}).thenApplyAsync(send -> { }).thenApplyAsync(send -> {
try (Buf buf = send.receive()) { try (Buffer buf = send.receive()) {
byte b = 0; byte b = 0;
while (buf.readableBytes() > 0) { while (buf.readableBytes() > 0) {
b += buf.readByte(); b += buf.readByte();

View File

@ -15,8 +15,8 @@
*/ */
package io.netty.buffer.api.benchmarks; package io.netty.buffer.api.benchmarks;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import io.netty.buffer.api.Send; import io.netty.buffer.api.Send;
import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.BenchmarkMode;
@ -40,27 +40,27 @@ import static java.util.concurrent.CompletableFuture.completedFuture;
@OutputTimeUnit(TimeUnit.MICROSECONDS) @OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark) @State(Scope.Benchmark)
public class SendBenchmark { public class SendBenchmark {
private static final Allocator NON_POOLED = Allocator.heap(); private static final BufferAllocator NON_POOLED = BufferAllocator.heap();
private static final Allocator POOLED = Allocator.pooledHeap(); private static final BufferAllocator POOLED = BufferAllocator.pooledHeap();
private static final Function<Send<Buf>, Send<Buf>> BUFFER_BOUNCE = send -> { private static final Function<Send<Buffer>, Send<Buffer>> BUFFER_BOUNCE = send -> {
try (Buf buf = send.receive()) { try (Buffer buf = send.receive()) {
return buf.send(); return buf.send();
} }
}; };
@Benchmark @Benchmark
public Buf sendNonPooled() throws Exception { public Buffer sendNonPooled() throws Exception {
try (Buf buf = NON_POOLED.allocate(8)) { try (Buffer buf = NON_POOLED.allocate(8)) {
try (Buf receive = completedFuture(buf.send()).thenApplyAsync(BUFFER_BOUNCE).get().receive()) { try (Buffer receive = completedFuture(buf.send()).thenApplyAsync(BUFFER_BOUNCE).get().receive()) {
return receive; return receive;
} }
} }
} }
@Benchmark @Benchmark
public Buf sendPooled() throws Exception { public Buffer sendPooled() throws Exception {
try (Buf buf = POOLED.allocate(8)) { try (Buffer buf = POOLED.allocate(8)) {
try (Buf receive = completedFuture(buf.send()).thenApplyAsync(BUFFER_BOUNCE).get().receive()) { try (Buffer receive = completedFuture(buf.send()).thenApplyAsync(BUFFER_BOUNCE).get().receive()) {
return receive; return receive;
} }
} }

View File

@ -15,25 +15,25 @@
*/ */
package io.netty.buffer.api.examples; package io.netty.buffer.api.examples;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import static java.lang.System.out; import static java.lang.System.out;
import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.CompletableFuture.completedFuture;
public final class AsyncExample { public final class AsyncExample {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
try (Allocator allocator = Allocator.pooledDirect(); try (BufferAllocator allocator = BufferAllocator.pooledDirect();
Buf startBuf = allocator.allocate(16)) { Buffer startBuf = allocator.allocate(16)) {
startBuf.writeLong(threadId()); startBuf.writeLong(threadId());
completedFuture(startBuf.send()).thenApplyAsync(send -> { completedFuture(startBuf.send()).thenApplyAsync(send -> {
try (Buf buf = send.receive()) { try (Buffer buf = send.receive()) {
buf.writeLong(threadId()); buf.writeLong(threadId());
return buf.send(); return buf.send();
} }
}).thenAcceptAsync(send -> { }).thenAcceptAsync(send -> {
try (Buf buf = send.receive()) { try (Buffer buf = send.receive()) {
out.println("First thread id was " + buf.readLong()); out.println("First thread id was " + buf.readLong());
out.println("Then sent to " + buf.readLong()); out.println("Then sent to " + buf.readLong());
out.println("And now in thread " + threadId()); out.println("And now in thread " + threadId());

View File

@ -15,23 +15,23 @@
*/ */
package io.netty.buffer.api.examples; package io.netty.buffer.api.examples;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import io.netty.buffer.api.Scope; import io.netty.buffer.api.Scope;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
public final class ComposingAndSlicingExample { public final class ComposingAndSlicingExample {
public static void main(String[] args) { public static void main(String[] args) {
try (Allocator allocator = Allocator.pooledDirect(); try (BufferAllocator allocator = BufferAllocator.pooledDirect();
Buf buf = createBigBuffer(allocator)) { Buffer buf = createBigBuffer(allocator)) {
ThreadLocalRandom tlr = ThreadLocalRandom.current(); ThreadLocalRandom tlr = ThreadLocalRandom.current();
for (int i = 0; i < tlr.nextInt(4, 200); i++) { for (int i = 0; i < tlr.nextInt(4, 200); i++) {
buf.writeByte((byte) tlr.nextInt()); buf.writeByte((byte) tlr.nextInt());
} }
try (Buf slice = buf.slice()) { try (Buffer slice = buf.slice()) {
slice.send(); slice.send();
System.out.println("buf.capacity() = " + buf.capacity()); System.out.println("buf.capacity() = " + buf.capacity());
System.out.println("buf.readableBytes() = " + buf.readableBytes()); System.out.println("buf.readableBytes() = " + buf.readableBytes());
@ -42,7 +42,7 @@ public final class ComposingAndSlicingExample {
} }
} }
private static Buf createBigBuffer(Allocator allocator) { private static Buffer createBigBuffer(BufferAllocator allocator) {
try (Scope scope = new Scope()) { try (Scope scope = new Scope()) {
return allocator.compose( return allocator.compose(
scope.add(allocator.allocate(64)), scope.add(allocator.allocate(64)),

View File

@ -15,8 +15,8 @@
*/ */
package io.netty.buffer.api.examples; package io.netty.buffer.api.examples;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import io.netty.buffer.api.Send; import io.netty.buffer.api.Send;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
@ -33,15 +33,15 @@ import static java.nio.file.StandardOpenOption.WRITE;
public final class FileCopyExample { public final class FileCopyExample {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2); ExecutorService executor = Executors.newFixedThreadPool(2);
ArrayBlockingQueue<Send<Buf>> queue = new ArrayBlockingQueue<>(8); ArrayBlockingQueue<Send<Buffer>> queue = new ArrayBlockingQueue<>(8);
try (Allocator allocator = Allocator.pooledDirect(); try (BufferAllocator allocator = BufferAllocator.pooledDirect();
var input = FileChannel.open(Path.of("/dev/urandom"), READ); var input = FileChannel.open(Path.of("/dev/urandom"), READ);
var output = FileChannel.open(Path.of("random.bin"), CREATE, TRUNCATE_EXISTING, WRITE)) { var output = FileChannel.open(Path.of("random.bin"), CREATE, TRUNCATE_EXISTING, WRITE)) {
Send<Buf> done = allocator.compose().send(); Send<Buffer> done = allocator.compose().send();
var reader = executor.submit(() -> { var reader = executor.submit(() -> {
for (int i = 0; i < 1024; i++) { for (int i = 0; i < 1024; i++) {
try (Buf in = allocator.allocate(1024)) { try (Buffer in = allocator.allocate(1024)) {
System.out.println("in = " + in); System.out.println("in = " + in);
in.forEachWritable(0, (index, component) -> { in.forEachWritable(0, (index, component) -> {
var bb = component.writableBuffer(); var bb = component.writableBuffer();
@ -59,9 +59,9 @@ public final class FileCopyExample {
}); });
var writer = executor.submit(() -> { var writer = executor.submit(() -> {
Send<Buf> send; Send<Buffer> send;
while ((send = queue.take()) != done) { while ((send = queue.take()) != done) {
try (Buf out = send.receive()) { try (Buffer out = send.receive()) {
System.out.println("Received " + out.readableBytes() + " bytes."); System.out.println("Received " + out.readableBytes() + " bytes.");
out.forEachReadable(0, (index, component) -> { out.forEachReadable(0, (index, component) -> {
var bb = component.readableBuffer(); var bb = component.readableBuffer();

View File

@ -15,8 +15,8 @@
*/ */
package io.netty.buffer.api.examples; package io.netty.buffer.api.examples;
import io.netty.buffer.api.Allocator; import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.Buf; import io.netty.buffer.api.Buffer;
import io.netty.buffer.api.Send; import io.netty.buffer.api.Send;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
@ -31,7 +31,7 @@ public class SendExample {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ExecutorService executor = ExecutorService executor =
newSingleThreadExecutor(); newSingleThreadExecutor();
Allocator allocator = Allocator.heap(); BufferAllocator allocator = BufferAllocator.heap();
var future = beginTask(executor, allocator); var future = beginTask(executor, allocator);
future.get(); future.get();
@ -41,17 +41,17 @@ public class SendExample {
} }
private static Future<?> beginTask( private static Future<?> beginTask(
ExecutorService executor, Allocator allocator) { ExecutorService executor, BufferAllocator allocator) {
try (Buf buf = allocator.allocate(32)) { try (Buffer buf = allocator.allocate(32)) {
// !!! pit-fall: buffer life-time ends before task completes // !!! pit-fall: buffer life-time ends before task completes
return executor.submit(new Task(buf)); return executor.submit(new Task(buf));
} }
} }
private static class Task implements Runnable { private static class Task implements Runnable {
private final Buf buf; private final Buffer buf;
Task(Buf buf) { Task(Buffer buf) {
this.buf = buf; this.buf = buf;
} }
@ -68,7 +68,7 @@ public class SendExample {
static final class Ex2 { static final class Ex2 {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ExecutorService executor = newSingleThreadExecutor(); ExecutorService executor = newSingleThreadExecutor();
Allocator allocator = Allocator.heap(); BufferAllocator allocator = BufferAllocator.heap();
var future = beginTask(executor, allocator); var future = beginTask(executor, allocator);
future.get(); future.get();
@ -78,17 +78,17 @@ public class SendExample {
} }
private static Future<?> beginTask( private static Future<?> beginTask(
ExecutorService executor, Allocator allocator) { ExecutorService executor, BufferAllocator allocator) {
try (Buf buf = allocator.allocate(32)) { try (Buffer buf = allocator.allocate(32)) {
// !!! pit-fall: Rc decrement in other thread. // !!! pit-fall: Rc decrement in other thread.
return executor.submit(new Task(buf.acquire())); return executor.submit(new Task(buf.acquire()));
} }
} }
private static class Task implements Runnable { private static class Task implements Runnable {
private final Buf buf; private final Buffer buf;
Task(Buf buf) { Task(Buffer buf) {
this.buf = buf; this.buf = buf;
} }
@ -107,7 +107,7 @@ public class SendExample {
static final class Ex3 { static final class Ex3 {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ExecutorService executor = newSingleThreadExecutor(); ExecutorService executor = newSingleThreadExecutor();
Allocator allocator = Allocator.heap(); BufferAllocator allocator = BufferAllocator.heap();
var future = beginTask(executor, allocator); var future = beginTask(executor, allocator);
future.get(); future.get();
@ -117,22 +117,22 @@ public class SendExample {
} }
private static Future<?> beginTask( private static Future<?> beginTask(
ExecutorService executor, Allocator allocator) { ExecutorService executor, BufferAllocator allocator) {
try (Buf buf = allocator.allocate(32)) { try (Buffer buf = allocator.allocate(32)) {
return executor.submit(new Task(buf.send())); return executor.submit(new Task(buf.send()));
} }
} }
private static class Task implements Runnable { private static class Task implements Runnable {
private final Send<Buf> send; private final Send<Buffer> send;
Task(Send<Buf> send) { Task(Send<Buffer> send) {
this.send = send; this.send = send;
} }
@Override @Override
public void run() { public void run() {
try (Buf buf = send.receive()) { try (Buffer buf = send.receive()) {
while (buf.writableBytes() > 0) { while (buf.writableBytes() > 0) {
buf.writeByte((byte) 42); buf.writeByte((byte) 42);
} }
@ -144,9 +144,9 @@ public class SendExample {
static final class Ex4 { static final class Ex4 {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ExecutorService executor = newFixedThreadPool(4); ExecutorService executor = newFixedThreadPool(4);
Allocator allocator = Allocator.heap(); BufferAllocator allocator = BufferAllocator.heap();
try (Buf buf = allocator.allocate(4096)) { try (Buffer buf = allocator.allocate(4096)) {
// !!! pit-fall: Rc decrement in other thread. // !!! pit-fall: Rc decrement in other thread.
var futA = executor.submit(new Task(buf.slice(0, 1024))); var futA = executor.submit(new Task(buf.slice(0, 1024)));
var futB = executor.submit(new Task(buf.slice(1024, 1024))); var futB = executor.submit(new Task(buf.slice(1024, 1024)));
@ -163,9 +163,9 @@ public class SendExample {
} }
private static class Task implements Runnable { private static class Task implements Runnable {
private final Buf slice; private final Buffer slice;
Task(Buf slice) { Task(Buffer slice) {
this.slice = slice; this.slice = slice;
} }
@ -183,13 +183,13 @@ public class SendExample {
static final class Ex5 { static final class Ex5 {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ExecutorService executor = newFixedThreadPool(4); ExecutorService executor = newFixedThreadPool(4);
Allocator allocator = Allocator.heap(); BufferAllocator allocator = BufferAllocator.heap();
try (Buf buf = allocator.allocate(4096); try (Buffer buf = allocator.allocate(4096);
Buf sliceA = buf.slice(0, 1024); Buffer sliceA = buf.slice(0, 1024);
Buf sliceB = buf.slice(1024, 1024); Buffer sliceB = buf.slice(1024, 1024);
Buf sliceC = buf.slice(2048, 1024); Buffer sliceC = buf.slice(2048, 1024);
Buf sliceD = buf.slice(3072, 1024)) { Buffer sliceD = buf.slice(3072, 1024)) {
var futA = executor.submit(new Task(sliceA)); var futA = executor.submit(new Task(sliceA));
var futB = executor.submit(new Task(sliceB)); var futB = executor.submit(new Task(sliceB));
var futC = executor.submit(new Task(sliceC)); var futC = executor.submit(new Task(sliceC));
@ -205,9 +205,9 @@ public class SendExample {
} }
private static class Task implements Runnable { private static class Task implements Runnable {
private final Buf slice; private final Buffer slice;
Task(Buf slice) { Task(Buffer slice) {
this.slice = slice; this.slice = slice;
} }
@ -223,9 +223,9 @@ public class SendExample {
static final class Ex6 { static final class Ex6 {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ExecutorService executor = newFixedThreadPool(4); ExecutorService executor = newFixedThreadPool(4);
Allocator allocator = Allocator.heap(); BufferAllocator allocator = BufferAllocator.heap();
try (Buf buf = allocator.allocate(4096)) { try (Buffer buf = allocator.allocate(4096)) {
var futA = executor.submit(new Task(buf.writerOffset(1024).bifurcate().send())); var futA = executor.submit(new Task(buf.writerOffset(1024).bifurcate().send()));
var futB = executor.submit(new Task(buf.writerOffset(1024).bifurcate().send())); var futB = executor.submit(new Task(buf.writerOffset(1024).bifurcate().send()));
var futC = executor.submit(new Task(buf.writerOffset(1024).bifurcate().send())); var futC = executor.submit(new Task(buf.writerOffset(1024).bifurcate().send()));
@ -241,15 +241,15 @@ public class SendExample {
} }
private static class Task implements Runnable { private static class Task implements Runnable {
private final Send<Buf> send; private final Send<Buffer> send;
Task(Send<Buf> send) { Task(Send<Buffer> send) {
this.send = send; this.send = send;
} }
@Override @Override
public void run() { public void run() {
try (Buf buf = send.receive().writerOffset(0)) { try (Buffer buf = send.receive().writerOffset(0)) {
while (buf.writableBytes() > 0) { while (buf.writableBytes() > 0) {
buf.writeByte((byte) 42); buf.writeByte((byte) 42);
} }