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.
* 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.
*/
public interface AllocatorControl {
@ -25,19 +25,19 @@ public interface AllocatorControl {
* Allocate a buffer that is not tethered to any particular {@link Drop} implementation,
* and return the recoverable memory object from it.
* <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.
*
* @param originator The buffer that originated the request for an untethered memory allocated.
* @param size The size of the requested memory allocation, in bytes.
* @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.
* 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.
*/

View File

@ -30,8 +30,9 @@ import java.nio.ByteOrder;
*
* <h3>Creating a buffer</h3>
*
* Buffers are created by {@linkplain Allocator 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.
* 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 BufferAllocator}
* interface.
*
* <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.
* That is to say, all {@linkplain #acquire() acquires} must have been paired with a {@link #close()};
* 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.
* 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.
@ -106,14 +107,14 @@ import java.nio.ByteOrder;
* </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.
*
* @param order The new default byte order, used by accessor methods that don't use an explicit byte order.
* @return This buffer instance.
*/
Buf order(ByteOrder order);
Buffer order(ByteOrder order);
/**
* 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.
*
* @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
* {@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.
@ -156,12 +157,12 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* Set the writer offset. Make the next write happen at the given offset.
*
* @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
* {@link #readerOffset()} or greater than {@link #capacity()}.
* @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())}.
@ -183,10 +184,10 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* #writerOffset()} are not modified.
*
* @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}.
*/
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.
@ -199,7 +200,7 @@ public interface Buf extends Rc<Buf>, BufAccessors {
*
* @return this buffer.
*/
Buf readOnly(boolean readOnly);
Buffer readOnly(boolean readOnly);
/**
* 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()},
* that is a view of the readable region of this buffer.
*/
default Buf slice() {
default Buffer slice() {
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()},
* 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
@ -303,13 +304,13 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* @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.
*/
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
* buffer to their initial values.
*/
default Buf reset() {
default Buffer reset() {
readerOffset(0);
writerOffset(0);
return this;
@ -386,8 +387,8 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* bytes.
* 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 does not already have the necessary space, then it will be expanded using the {@link Allocator}
* the buffer was created with.
* If this buffer does not already have the necessary space, then it will be expanded using the
* {@link BufferAllocator} the buffer was created with.
* This method is the same as calling {@link #ensureWritable(int, boolean)} where {@code allowCompaction} is
* {@code false}.
*
@ -418,8 +419,8 @@ public interface Buf extends Rc<Buf>, BufAccessors {
* </li>
* <li>
* 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
* buffer was created with.
* by just allocating more or larger buffers. This allocation would use the same {@link BufferAllocator}
* that this buffer was created with.
* </li>
* <li>
* 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.
*/
Buf bifurcate();
Buffer bifurcate();
/**
* 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;
/**
* 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.
* 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.
*/
public interface BufAccessors {
public interface BufferAccessors {
// <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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Byte#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Byte#BYTES}.
*/
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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Byte#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Byte#BYTES}.
*/
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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Byte#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Byte#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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.
* 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.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than 2.
* @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than 2.
*/
char readChar();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus 2.
* greater than {@link Buffer#capacity()} minus 2.
*/
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.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than 2.
* @return This Buffer.
* @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,
* 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 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
* 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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Short#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Short#BYTES}.
*/
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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Short#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Short#BYTES}.
*/
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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Short#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Short#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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.
* 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.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than 3.
* @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than 3.
*/
int readMedium();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus 3.
* greater than {@link Buffer#capacity()} minus 3.
*/
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.
* 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.
* @throws IndexOutOfBoundsException If {@link Buf#readableBytes} is less than 3.
* @throws IndexOutOfBoundsException If {@link Buffer#readableBytes} is less than 3.
*/
int readUnsignedMedium();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus 3.
* greater than {@link Buffer#capacity()} minus 3.
*/
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.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than 3.
* @return This Buffer.
* @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,
* 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 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
* 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.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than 3.
* @return This Buffer.
* @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,
* 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 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
* 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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Integer#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Integer#BYTES}.
*/
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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Integer#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Integer#BYTES}.
*/
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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Integer#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Integer#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Float#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Float#BYTES}.
*/
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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Float#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Long#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Long#BYTES}.
*/
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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Long#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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}.
* 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.
* @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();
/**
* 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,
* 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.
* @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
* greater than {@link Buf#capacity()} minus {@link Double#BYTES}.
* greater than {@link Buffer#capacity()} minus {@link Double#BYTES}.
*/
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}.
* 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.
* @return This Buf.
* @throws IndexOutOfBoundsException If {@link Buf#writableBytes} is less than {@link Double#BYTES}.
* @return This Buffer.
* @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,
* 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 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
* 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>
}

View File

@ -18,9 +18,9 @@ package io.netty.buffer.api;
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) {
if (size < 1) {
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
* not enough free memory available to allocate a {@link Buf} of the requested size.
* Allocate a {@link Buffer} of the given size in bytes. This method may throw an {@link OutOfMemoryError} if there
* is not enough free memory available to allocate a {@link Buffer} of the requested size.
* <p>
* The buffer will use the current platform native byte order by default, for accessor methods that don't have an
* explicit byte order.
*
* @param size The size of {@link Buf} to allocate.
* @return The newly allocated {@link Buf}.
* @param size The size of {@link Buffer} to allocate.
* @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
* not enough free memory available to allocate a {@link Buf} of the requested size.
* Allocate a {@link Buffer} of the given size in bytes. This method may throw an {@link OutOfMemoryError} if there
* is not enough free memory available to allocate a {@link Buffer} of the requested size.
* <p>
* 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.
* @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);
}
@ -68,18 +68,18 @@ public interface Allocator extends AutoCloseable {
* 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:
* <pre>{@code
* try (Buf a = allocator.allocate(size);
* Buf b = allocator.allocate(size)) {
* try (Buffer a = allocator.allocate(size);
* Buffer b = allocator.allocate(size)) {
* 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.
* }</pre>
* <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
* {@linkplain Rc#isOwned() owned state}.
* This means that the composite buffer must be the only reference to the constituent buffers.
* <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,
* and changing the byte order of the constituent buffers so they become inconsistent after construction,
* will result in unspecified behaviour.
@ -99,16 +99,17 @@ public interface Allocator extends AutoCloseable {
* <p>
* It is not a requirement that the buffers have the same size.
* <p>
* It is not a requirement that the buffers are allocated by this allocator, but if {@link Buf#ensureWritable(int)}
* is called on the composed buffer, and the composed buffer needs to be expanded, then this allocator instance
* will be used for allocation the extra memory.
* It is not a requirement that the buffers are allocated by this allocator, but if
* {@link Buffer#ensureWritable(int)} is called on the composed buffer, and the composed buffer needs to be
* expanded, then this allocator instance will be used for allocation the extra memory.
*
* @param bufs The buffers to compose into a single buffer view.
* @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) {
return new CompositeBuf(this, bufs);
default Buffer compose(Deref<Buffer>... bufs) {
return new CompositeBuffer(this, bufs);
}
/**
@ -122,13 +123,13 @@ public interface Allocator extends AutoCloseable {
* extension buffer.
* @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)) {
throw new IllegalArgumentException(
"Expected the first buffer to be a composite buffer, " +
"but it is a " + composite.getClass() + " buffer: " + composite + '.');
}
CompositeBuf buf = (CompositeBuf) composite;
CompositeBuffer buf = (CompositeBuffer) composite;
buf.extendWith(extension);
}
@ -137,8 +138,8 @@ public interface Allocator extends AutoCloseable {
* @param composite The buffer to check.
* @return {@code true} if the given buffer was created with {@link #compose(Deref...)}, {@code false} otherwise.
*/
static boolean isComposite(Buf composite) {
return composite.getClass() == CompositeBuf.class;
static boolean isComposite(Buffer composite) {
return composite.getClass() == CompositeBuffer.class;
}
/**
@ -149,19 +150,19 @@ public interface Allocator extends AutoCloseable {
default void close() {
}
static Allocator heap() {
return new ManagedAllocator(MemoryManager.getHeapMemoryManager(), Statics.CLEANER);
static BufferAllocator heap() {
return new ManagedBufferAllocator(MemoryManager.getHeapMemoryManager(), Statics.CLEANER);
}
static Allocator direct() {
return new ManagedAllocator(MemoryManager.getNativeMemoryManager(), Statics.CLEANER);
static BufferAllocator direct() {
return new ManagedBufferAllocator(MemoryManager.getNativeMemoryManager(), Statics.CLEANER);
}
static Allocator pooledHeap() {
static BufferAllocator pooledHeap() {
return new SizeClassedMemoryPool(MemoryManager.getHeapMemoryManager());
}
static Allocator pooledDirect() {
static BufferAllocator pooledDirect() {
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;
/**
* The {@link BufHolder} is an abstract class that simplifies the implementation of objects that themselves contain
* a {@link Buf} instance.
* The {@link BufferHolder} is an abstract class that simplifies the implementation of objects that themselves contain
* a {@link Buffer} instance.
* <p>
* The {@link BufHolder} 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
* inspiration.
* 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 BufferHolder}
* as inspiration.
* <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
* {@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> {
private static final VarHandle BUF = findVarHandle(lookup(), BufHolder.class, "buf", Buf.class);
private Buf buf;
public abstract class BufferHolder<T extends BufferHolder<T>> implements Rc<T> {
private static final VarHandle BUF = findVarHandle(lookup(), BufferHolder.class, "buf", Buffer.class);
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>
* <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();
}
/**
* 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>
* 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();
}
@ -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.
* The {@link BufHolder} should return a new concrete instance, that wraps the given {@link Buf} object.
* Called when a {@linkplain #send() sent} {@link BufferHolder} is received by the recipient.
* 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,
* and needs to be wrapped in a new {@link BufHolder} instance.
* @return A new {@linkplain T buffer holder} instance, containing the given {@linkplain Buf buffer}.
* @param buf The {@link Buffer} that is {@linkplain Send#receive() received} by the recipient,
* and needs to be wrapped in a new {@link BufferHolder} instance.
* @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.
* <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>
* <strong>Note:</strong> this method decreases the reference count of the current buffer,
* and increases the reference count of the new buffer.
* <p>
* 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) {
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.
* <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>
* <strong>Note:</strong> this method decreases the reference count of the current buffer,
* and takes exclusive ownership of the sent buffer.
* <p>
* 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) {
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.
* <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>
* <strong>Note:</strong> this method decreases the reference count of the current buffer,
* and increases the reference count of the new buffer.
* <p>
* 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) {
var prev = (Buf) BUF.getAndSet(this, newBuf.acquire());
protected final void replaceBufVolatile(Buffer newBuf) {
var prev = (Buffer) BUF.getAndSet(this, newBuf.acquire());
prev.close();
}
/**
* Replace the underlying referenced buffer with the given buffer.
* <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>
* <strong>Note:</strong> this method decreases the reference count of the current buffer,
* and takes exclusive ownership of the sent buffer.
* <p>
* 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) {
var prev = (Buf) BUF.getAndSet(this, send.receive());
protected final void replaceBufVolatile(Send<Buffer> send) {
var prev = (Buffer) BUF.getAndSet(this, send.receive());
prev.close();
}
/**
* Access the held {@link Buf} instance.
* Access the held {@link Buffer} instance.
* <p>
* 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;
}
/**
* Access the held {@link Buf} instance.
* Access the held {@link Buffer} instance.
* <p>
* 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() {
return (Buf) BUF.getVolatile(this);
protected final Buffer getBufVolatile() {
return (Buffer) BUF.getVolatile(this);
}
}

View File

@ -20,16 +20,16 @@ import java.lang.invoke.VarHandle;
/**
* 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.
*
* @param buf The buffer to reference.
*/
public BufRef(Buf buf) {
public BufferRef(Buffer 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();
}
@ -38,15 +38,15 @@ public final class BufRef extends BufHolder<BufRef> {
*
* @param send The {@linkplain Send sent} buffer to take ownership of.
*/
public BufRef(Send<Buf> send) {
public BufferRef(Send<Buffer> 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();
}
@Override
protected BufRef receive(Buf buf) {
return new BufRef(buf);
protected BufferRef receive(Buffer buf) {
return new BufferRef(buf);
}
/**
@ -57,9 +57,9 @@ public final class BufRef extends BufHolder<BufRef> {
* <p>
* 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);
}
@ -71,9 +71,9 @@ public final class BufRef extends BufHolder<BufRef> {
* <p>
* 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);
}
@ -82,7 +82,7 @@ public final class BufRef extends BufHolder<BufRef> {
*
* @return The buffer held by the reference.
*/
public Buf contents() {
public Buffer contents() {
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 java.lang.invoke.MethodHandles.lookup;
class CleanerPooledDrop implements Drop<Buf> {
class CleanerPooledDrop implements Drop<Buffer> {
private static final VarHandle CLEANABLE =
findVarHandle(lookup(), CleanerPooledDrop.class, "cleanable", GatedCleanable.class);
private final SizeClassedMemoryPool pool;
private final MemoryManager manager;
private final Drop<Buf> delegate;
private final Drop<Buffer> delegate;
@SuppressWarnings("unused")
private volatile GatedCleanable cleanable;
CleanerPooledDrop(SizeClassedMemoryPool pool, MemoryManager manager,
Drop<Buf> delegate) {
Drop<Buffer> delegate) {
this.pool = pool;
this.manager = manager;
this.delegate = delegate;
}
@Override
public void drop(Buf buf) {
public void drop(Buffer buf) {
GatedCleanable c = (GatedCleanable) CLEANABLE.getAndSet(this, null);
if (c != null) {
c.clean();
@ -49,7 +49,7 @@ class CleanerPooledDrop implements Drop<Buf> {
}
@Override
public void attach(Buf buf) {
public void attach(Buffer buf) {
// Unregister old cleanable, if any, to avoid uncontrolled build-up.
GatedCleanable c = (GatedCleanable) CLEANABLE.getAndSet(this, null);
if (c != null) {
@ -60,11 +60,11 @@ class CleanerPooledDrop implements Drop<Buf> {
var pool = this.pool;
var mem = manager.unwrapRecoverableMemory(buf);
var delegate = this.delegate;
WeakReference<Buf> ref = new WeakReference<>(buf);
WeakReference<Buffer> ref = new WeakReference<>(buf);
AtomicBoolean gate = new AtomicBoolean(true);
cleanable = new GatedCleanable(gate, CLEANER.register(this, () -> {
if (gate.getAndSet(false)) {
Buf b = ref.get();
Buffer b = ref.get();
if (b == null) {
pool.recoverMemory(mem);
} else {

View File

@ -18,8 +18,9 @@ package io.netty.buffer.api;
import java.nio.ByteBuffer;
/**
* This interface contain a collection of APIs used in the {@link Buf#forEachReadable(int, ReadableComponentProcessor)}
* and {@link Buf#forEachWritable(int, WritableComponentProcessor)} methods.
* This interface contain a collection of APIs used in the
* {@link Buffer#forEachReadable(int, ReadableComponentProcessor)} and
* {@link Buffer#forEachWritable(int, WritableComponentProcessor)} methods.
*/
public interface ComponentProcessor {
/**
@ -29,14 +30,14 @@ public interface ComponentProcessor {
interface ReadableComponentProcessor<E extends Exception> extends ComponentProcessor {
/**
* Process the given component at the given index in the
* {@link Buf#forEachReadable(int, ReadableComponentProcessor) iteration}.
* {@link Buffer#forEachReadable(int, ReadableComponentProcessor) iteration}.
* <p>
* 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
* {@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
* {@link Buf#forEachReadable(int, ReadableComponentProcessor)} method.
* {@link Buffer#forEachReadable(int, ReadableComponentProcessor)} method.
* @param component The current buffer component being processed.
* @return {@code true} if the iteration should continue and more components should be processed, otherwise
* {@code false} to stop the iteration early.
@ -51,14 +52,14 @@ public interface ComponentProcessor {
interface WritableComponentProcessor<E extends Exception> extends ComponentProcessor {
/**
* Process the given component at the given index in the
* {@link Buf#forEachWritable(int, WritableComponentProcessor)} iteration}.
* {@link Buffer#forEachWritable(int, WritableComponentProcessor)} iteration}.
* <p>
* 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
* {@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
* {@link Buf#forEachWritable(int, WritableComponentProcessor)} method.
* {@link Buffer#forEachWritable(int, WritableComponentProcessor)} method.
* @param component The current buffer component being processed.
* @return {@code true} if the iteration should continue and more components should be processed, otherwise
* {@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
* {@link Buf#forEachReadable(int, ReadableComponentProcessor)}.
* {@link Buffer#forEachReadable(int, ReadableComponentProcessor)}.
*/
interface ReadableComponent {
@ -116,7 +117,8 @@ public interface ComponentProcessor {
* Get a {@link ByteBuffer} instance for this memory component.
* <p>
* <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.
*/
@ -126,7 +128,7 @@ public interface ComponentProcessor {
/**
* 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 {

View File

@ -27,24 +27,24 @@ import java.util.Objects;
import java.util.Set;
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}.
* 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.
*/
private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;
private static final Drop<CompositeBuf> COMPOSITE_DROP = buf -> {
for (Buf b : buf.bufs) {
private static final Drop<CompositeBuffer> COMPOSITE_DROP = buf -> {
for (Buffer b : buf.bufs) {
b.close();
}
buf.makeInaccessible();
};
private final Allocator allocator;
private final TornBufAccessors tornBufAccessors;
private final BufferAllocator allocator;
private final TornBufferAccessors tornBufAccessors;
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 capacity;
private int roff;
@ -54,11 +54,11 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
private boolean closed;
private boolean readOnly;
CompositeBuf(Allocator allocator, Deref<Buf>[] refs) {
CompositeBuffer(BufferAllocator allocator, Deref<Buffer>[] refs) {
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,
// 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
@ -66,16 +66,16 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
// This restriction guarantees that methods like countComponents, forEachReadable and forEachWritable,
// will never overflow their component counts.
// Allocating a new array unconditionally also prevents external modification of the array.
Buf[] bufs = Arrays.stream(refs)
.map(r -> r.get()) // Increments reference counts.
.filter(CompositeBuf::discardEmpty)
.flatMap(CompositeBuf::flattenBuffer)
.toArray(Buf[]::new);
Buffer[] bufs = Arrays.stream(refs)
.map(r -> r.get()) // Increments reference counts.
.filter(CompositeBuffer::discardEmpty)
.flatMap(CompositeBuffer::flattenBuffer)
.toArray(Buffer[]::new);
// 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));
if (duplicatesCheck.size() < bufs.length) {
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
buf.close(); // Undo the increment we did with Deref.get().
}
throw new IllegalArgumentException(
@ -84,7 +84,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
return bufs;
}
private static boolean discardEmpty(Buf buf) {
private static boolean discardEmpty(Buffer buf) {
if (buf.capacity() > 0) {
return true;
} else {
@ -95,12 +95,12 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
}
private static Stream<Buf> flattenBuffer(Buf buf) {
if (buf instanceof CompositeBuf) {
private static Stream<Buffer> flattenBuffer(Buffer buf) {
if (buf instanceof CompositeBuffer) {
// 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;
for (Buf b : bufs) {
for (Buffer b : bufs) {
b.acquire();
}
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);
}
private CompositeBuf(Allocator allocator, boolean isSendable, Buf[] bufs, Drop<CompositeBuf> drop,
boolean acquireBufs) {
private CompositeBuffer(BufferAllocator allocator, boolean isSendable, Buffer[] bufs, Drop<CompositeBuffer> drop,
boolean acquireBufs) {
super(drop);
this.allocator = allocator;
this.isSendable = isSendable;
if (acquireBufs) {
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
buf.acquire();
}
}
try {
if (bufs.length > 0) {
ByteOrder targetOrder = bufs[0].order();
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
if (buf.order() != targetOrder) {
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();
boolean targetReadOnly = bufs[0].readOnly();
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
if (buf.readOnly() != targetReadOnly) {
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;
computeBufferOffsets();
tornBufAccessors = new TornBufAccessors(this);
tornBufAccessors = new TornBufferAccessors(this);
} catch (Exception e) {
// 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.
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
buf.close();
}
throw e;
@ -157,7 +157,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
int woff = 0;
int roff = 0;
boolean woffMidpoint = false;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
if (buf.writableBytes() == 0) {
woff += buf.capacity();
} else if (!woffMidpoint) {
@ -170,7 +170,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
}
boolean roffMidpoint = false;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
if (buf.readableBytes() == 0 && buf.writableBytes() == 0) {
roff += buf.capacity();
} else if (!roffMidpoint) {
@ -206,14 +206,14 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@Override
public String toString() {
return "Buf[roff:" + roff + ", woff:" + woff + ", cap:" + capacity + ']';
return "Buffer[roff:" + roff + ", woff:" + woff + ", cap:" + capacity + ']';
}
@Override
public Buf order(ByteOrder order) {
public Buffer order(ByteOrder order) {
if (this.order != order) {
this.order = order;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
buf.order(order);
}
}
@ -236,10 +236,10 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf readerOffset(int index) {
public Buffer readerOffset(int index) {
prepRead(index, 0);
int indexLeft = index;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
buf.readerOffset(Math.min(indexLeft, buf.capacity()));
indexLeft = Math.max(0, indexLeft - buf.capacity());
}
@ -253,10 +253,10 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writerOffset(int index) {
public Buffer writerOffset(int index) {
checkWriteBounds(index, 0);
int indexLeft = index;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
buf.writerOffset(Math.min(indexLeft, buf.capacity()));
indexLeft = Math.max(0, indexLeft - buf.capacity());
}
@ -265,8 +265,8 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf fill(byte value) {
for (Buf buf : bufs) {
public Buffer fill(byte value) {
for (Buffer buf : bufs) {
buf.fill(value);
}
return this;
@ -278,8 +278,8 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf readOnly(boolean readOnly) {
for (Buf buf : bufs) {
public Buffer readOnly(boolean readOnly) {
for (Buffer buf : bufs) {
buf.readOnly(readOnly);
}
this.readOnly = readOnly;
@ -292,24 +292,24 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf slice(int offset, int length) {
public Buffer slice(int offset, int length) {
checkWriteBounds(offset, length);
if (offset < 0 || length < 0) {
throw new IllegalArgumentException(
"Offset and length cannot be negative, but offset was " +
offset + ", and length was " + length + '.');
}
Buf choice = (Buf) chooseBuffer(offset, 0);
Buf[] slices = null;
Buffer choice = (Buffer) chooseBuffer(offset, 0);
Buffer[] slices = null;
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.
COMPOSITE_DROP.drop(obj);
};
try {
if (length > 0) {
slices = new Buf[bufs.length];
slices = new Buffer[bufs.length];
int off = subOffset;
int cap = length;
int i;
@ -323,17 +323,17 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
slices = Arrays.copyOf(slices, i);
} else {
// 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) {
// We called acquire prior to the try-clause. We need to undo that if we're not creating a composite buffer:
close();
throw throwable;
} finally {
if (slices != null) {
for (Buf slice : slices) {
for (Buffer slice : slices) {
if (slice != null) {
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);
}
while (length > 0) {
var buf = (Buf) chooseBuffer(srcPos, 0);
var buf = (Buffer) chooseBuffer(srcPos, 0);
int toCopy = Math.min(buf.capacity() - subOffset, length);
dest.copyInto(buf, subOffset, destPos, toCopy);
srcPos += toCopy;
@ -374,11 +374,11 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@FunctionalInterface
private interface CopyInto {
void copyInto(Buf src, int srcPos, int destPos, int length);
void copyInto(Buffer src, int srcPos, int destPos, int length);
}
@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) {
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 off = fromOffset - offsets[startBufferIndex];
Buf startBuf = bufs[startBufferIndex];
Buffer startBuf = bufs[startBufferIndex];
ByteCursor startCursor = startBuf.openCursor(off, Math.min(startBuf.capacity() - off, length));
return new ByteCursor() {
int index = fromOffset;
@ -484,7 +484,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
private void nextCursor() {
bufferIndex++;
Buf nextBuf = bufs[bufferIndex];
Buffer nextBuf = bufs[bufferIndex];
cursor = nextBuf.openCursor(0, Math.min(nextBuf.capacity(), bytesLeft()));
initOffset = 0;
}
@ -523,7 +523,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
int startBufferIndex = searchOffsets(fromOffset);
int off = fromOffset - offsets[startBufferIndex];
Buf startBuf = bufs[startBufferIndex];
Buffer startBuf = bufs[startBufferIndex];
ByteCursor startCursor = startBuf.openReverseCursor(off, Math.min(off + 1, length));
return new ByteCursor() {
int index = fromOffset;
@ -585,7 +585,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
private void nextCursor() {
bufferIndex--;
Buf nextBuf = bufs[bufferIndex];
Buffer nextBuf = bufs[bufferIndex];
int length = Math.min(nextBuf.capacity(), bytesLeft());
int offset = nextBuf.capacity() - 1;
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.
// We always compact as much as is possible, regardless of size. This amortizes our work.
int compactableBuffers = 0;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
if (buf.capacity() != buf.readerOffset()) {
break;
}
compactableBuffers++;
}
if (compactableBuffers > 0) {
Buf[] compactable;
Buffer[] compactable;
if (compactableBuffers < bufs.length) {
compactable = new Buf[compactableBuffers];
compactable = new Buffer[compactableBuffers];
System.arraycopy(bufs, 0, compactable, 0, compactable.length);
System.arraycopy(bufs, compactable.length, bufs, 0, bufs.length - compactable.length);
System.arraycopy(compactable, 0, bufs, bufs.length - compactable.length, compactable.length);
} else {
compactable = bufs;
}
for (Buf buf : compactable) {
for (Buffer buf : compactable) {
buf.reset();
}
computeBufferOffsets();
@ -660,13 +660,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
long newSize = capacity() + (long) size;
Allocator.checkSize(newSize);
BufferAllocator.checkSize(newSize);
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);
}
void extendWith(Buf extension) {
void extendWith(Buffer extension) {
Objects.requireNonNull(extension, "Extension buffer cannot be null.");
if (!isOwned()) {
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;
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 {
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
// component buffers.
CompositeBuf compositeExtension = (CompositeBuf) extension;
Buf[] addedBuffers = compositeExtension.bufs;
Set<Buf> duplicatesCheck = Collections.newSetFromMap(new IdentityHashMap<>());
CompositeBuffer compositeExtension = (CompositeBuffer) extension;
Buffer[] addedBuffers = compositeExtension.bufs;
Set<Buffer> duplicatesCheck = Collections.newSetFromMap(new IdentityHashMap<>());
duplicatesCheck.addAll(Arrays.asList(bufs));
duplicatesCheck.addAll(Arrays.asList(addedBuffers));
if (duplicatesCheck.size() < bufs.length + addedBuffers.length) {
throw extensionDuplicatesException();
}
for (Buf addedBuffer : addedBuffers) {
for (Buffer addedBuffer : addedBuffers) {
addedBuffer.acquire();
}
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);
computeBufferOffsets();
} else {
for (Buf buf : restoreTemp) {
for (Buffer buf : restoreTemp) {
if (buf == extension) {
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.");
}
private void unsafeExtendWith(Buf extension) {
private void unsafeExtendWith(Buffer extension) {
bufs = Arrays.copyOf(bufs, bufs.length + 1);
bufs[bufs.length - 1] = extension;
computeBufferOffsets();
}
@Override
public Buf bifurcate() {
public Buffer bifurcate() {
if (!isOwned()) {
throw new IllegalStateException("Cannot bifurcate a buffer that is not owned.");
}
if (bufs.length == 0) {
// 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 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);
if (off > 0 && bifs.length > 0 && off < bifs[bifs.length - 1].capacity()) {
bifs[bifs.length - 1] = bufs[0].bifurcate();
}
computeBufferOffsets();
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.
return compositeBuf;
} finally {
// 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();
}
}
@ -810,7 +810,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@Override
public int countComponents() {
int sum = 0;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
sum += buf.countComponents();
}
return sum;
@ -819,7 +819,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@Override
public int countReadableComponents() {
int sum = 0;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
sum += buf.countReadableComponents();
}
return sum;
@ -828,7 +828,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
@Override
public int countWritableComponents() {
int sum = 0;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
sum += buf.countWritableComponents();
}
return sum;
@ -839,7 +839,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
throws E {
checkReadBounds(readerOffset(), Math.max(1, readableBytes()));
int visited = 0;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
if (buf.readableBytes() > 0) {
int count = buf.forEachReadable(visited + initialIndex, processor);
if (count > 0) {
@ -858,7 +858,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
throws E {
checkWriteBounds(writerOffset(), Math.max(1, writableBytes()));
int visited = 0;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
if (buf.writableBytes() > 0) {
int count = buf.forEachWritable(visited + initialIndex, processor);
if (count > 0) {
@ -894,25 +894,25 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeByte(byte value) {
public Buffer writeByte(byte value) {
prepWrite(Byte.BYTES).writeByte(value);
return this;
}
@Override
public Buf setByte(int woff, byte value) {
public Buffer setByte(int woff, byte value) {
prepWrite(woff, Byte.BYTES).setByte(subOffset, value);
return this;
}
@Override
public Buf writeUnsignedByte(int value) {
public Buffer writeUnsignedByte(int value) {
prepWrite(Byte.BYTES).writeUnsignedByte(value);
return this;
}
@Override
public Buf setUnsignedByte(int woff, int value) {
public Buffer setUnsignedByte(int woff, int value) {
prepWrite(woff, Byte.BYTES).setUnsignedByte(subOffset, value);
return this;
}
@ -928,13 +928,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeChar(char value) {
public Buffer writeChar(char value) {
prepWrite(2).writeChar(value);
return this;
}
@Override
public Buf setChar(int woff, char value) {
public Buffer setChar(int woff, char value) {
prepWrite(woff, 2).setChar(subOffset, value);
return this;
}
@ -960,25 +960,25 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeShort(short value) {
public Buffer writeShort(short value) {
prepWrite(Short.BYTES).writeShort(value);
return this;
}
@Override
public Buf setShort(int woff, short value) {
public Buffer setShort(int woff, short value) {
prepWrite(woff, Short.BYTES).setShort(subOffset, value);
return this;
}
@Override
public Buf writeUnsignedShort(int value) {
public Buffer writeUnsignedShort(int value) {
prepWrite(Short.BYTES).writeUnsignedShort(value);
return this;
}
@Override
public Buf setUnsignedShort(int woff, int value) {
public Buffer setUnsignedShort(int woff, int value) {
prepWrite(woff, Short.BYTES).setUnsignedShort(subOffset, value);
return this;
}
@ -1004,25 +1004,25 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeMedium(int value) {
public Buffer writeMedium(int value) {
prepWrite(3).writeMedium(value);
return this;
}
@Override
public Buf setMedium(int woff, int value) {
public Buffer setMedium(int woff, int value) {
prepWrite(woff, 3).setMedium(subOffset, value);
return this;
}
@Override
public Buf writeUnsignedMedium(int value) {
public Buffer writeUnsignedMedium(int value) {
prepWrite(3).writeUnsignedMedium(value);
return this;
}
@Override
public Buf setUnsignedMedium(int woff, int value) {
public Buffer setUnsignedMedium(int woff, int value) {
prepWrite(woff, 3).setUnsignedMedium(subOffset, value);
return this;
}
@ -1048,25 +1048,25 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeInt(int value) {
public Buffer writeInt(int value) {
prepWrite(Integer.BYTES).writeInt(value);
return this;
}
@Override
public Buf setInt(int woff, int value) {
public Buffer setInt(int woff, int value) {
prepWrite(woff, Integer.BYTES).setInt(subOffset, value);
return this;
}
@Override
public Buf writeUnsignedInt(long value) {
public Buffer writeUnsignedInt(long value) {
prepWrite(Integer.BYTES).writeUnsignedInt(value);
return this;
}
@Override
public Buf setUnsignedInt(int woff, long value) {
public Buffer setUnsignedInt(int woff, long value) {
prepWrite(woff, Integer.BYTES).setUnsignedInt(subOffset, value);
return this;
}
@ -1082,13 +1082,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeFloat(float value) {
public Buffer writeFloat(float value) {
prepWrite(Float.BYTES).writeFloat(value);
return this;
}
@Override
public Buf setFloat(int woff, float value) {
public Buffer setFloat(int woff, float value) {
prepWrite(woff, Float.BYTES).setFloat(subOffset, value);
return this;
}
@ -1104,13 +1104,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeLong(long value) {
public Buffer writeLong(long value) {
prepWrite(Long.BYTES).writeLong(value);
return this;
}
@Override
public Buf setLong(int woff, long value) {
public Buffer setLong(int woff, long value) {
prepWrite(woff, Long.BYTES).setLong(subOffset, value);
return this;
}
@ -1126,22 +1126,22 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeDouble(double value) {
public Buffer writeDouble(double value) {
prepWrite(Double.BYTES).writeDouble(value);
return this;
}
@Override
public Buf setDouble(int woff, double value) {
public Buffer setDouble(int woff, double value) {
prepWrite(woff, Double.BYTES).setDouble(subOffset, value);
return this;
}
// </editor-fold>
@Override
protected Owned<CompositeBuf> prepareSend() {
protected Owned<CompositeBuffer> prepareSend() {
@SuppressWarnings("unchecked")
Send<Buf>[] sends = new Send[bufs.length];
Send<Buffer>[] sends = new Send[bufs.length];
try {
for (int i = 0; i < bufs.length; i++) {
sends[i] = bufs[i].send();
@ -1160,14 +1160,14 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
throw throwable;
}
makeInaccessible();
return new Owned<CompositeBuf>() {
return new Owned<CompositeBuffer>() {
@Override
public CompositeBuf transferOwnership(Drop<CompositeBuf> drop) {
Buf[] received = new Buf[sends.length];
public CompositeBuffer transferOwnership(Drop<CompositeBuffer> drop) {
Buffer[] received = new Buffer[sends.length];
for (int i = 0; i < sends.length; i++) {
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;
drop.attach(composite);
return composite;
@ -1198,7 +1198,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
private boolean allConstituentsAreOwned() {
boolean result = true;
for (Buf buf : bufs) {
for (Buffer buf : bufs) {
result &= buf.isOwned();
}
return result;
@ -1228,13 +1228,13 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
buf.setUnsignedByte(subOffset, value);
}
private BufAccessors prepRead(int size) {
private BufferAccessors prepRead(int size) {
var buf = prepRead(roff, size);
roff += size;
return buf;
}
private BufAccessors prepRead(int index, int size) {
private BufferAccessors prepRead(int index, int size) {
checkReadBounds(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);
woff += size;
return buf;
}
private BufAccessors prepWrite(int index, int size) {
private BufferAccessors prepWrite(int index, int size) {
checkWriteBounds(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.");
}
private BufAccessors chooseBuffer(int index, int size) {
private BufferAccessors chooseBuffer(int index, int size) {
int i = searchOffsets(index);
if (i == bufs.length) {
// 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;
}
int off = index - offsets[i];
Buf candidate = bufs[i];
Buffer candidate = bufs[i];
if (off + size <= candidate.capacity()) {
subOffset = off;
return candidate;
@ -1299,7 +1299,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
return tornBufAccessors;
}
private BufAccessors choosePassThroughBuffer(int index) {
private BufferAccessors choosePassThroughBuffer(int index) {
int i = searchOffsets(index);
return bufs[i];
}
@ -1310,10 +1310,10 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
// <editor-fold defaultstate="collapsed" desc="Torn buffer access.">
private static final class TornBufAccessors implements BufAccessors {
private final CompositeBuf buf;
private static final class TornBufferAccessors implements BufferAccessors {
private final CompositeBuffer buf;
private TornBufAccessors(CompositeBuf buf) {
private TornBufferAccessors(CompositeBuffer buf) {
this.buf = buf;
}
@ -1338,22 +1338,22 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeByte(byte value) {
public Buffer writeByte(byte value) {
throw new AssertionError("Method should not be used.");
}
@Override
public Buf setByte(int woff, byte value) {
public Buffer setByte(int woff, byte value) {
throw new AssertionError("Method should not be used.");
}
@Override
public Buf writeUnsignedByte(int value) {
public Buffer writeUnsignedByte(int value) {
throw new AssertionError("Method should not be used.");
}
@Override
public Buf setUnsignedByte(int woff, int value) {
public Buffer setUnsignedByte(int woff, int value) {
throw new AssertionError("Method should not be used.");
}
@ -1376,7 +1376,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeChar(char value) {
public Buffer writeChar(char value) {
if (bigEndian()) {
write(value >>> 8);
write(value & 0xFF);
@ -1388,7 +1388,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf setChar(int woff, char value) {
public Buffer setChar(int woff, char value) {
if (bigEndian()) {
write(woff, value >>> 8);
write(woff + 1, value & 0xFF);
@ -1436,7 +1436,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeShort(short value) {
public Buffer writeShort(short value) {
if (bigEndian()) {
write(value >>> 8);
write(value & 0xFF);
@ -1448,7 +1448,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf setShort(int woff, short value) {
public Buffer setShort(int woff, short value) {
if (bigEndian()) {
write(woff, value >>> 8);
write(woff + 1, value & 0xFF);
@ -1460,7 +1460,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeUnsignedShort(int value) {
public Buffer writeUnsignedShort(int value) {
if (bigEndian()) {
write(value >>> 8);
write(value & 0xFF);
@ -1472,7 +1472,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf setUnsignedShort(int woff, int value) {
public Buffer setUnsignedShort(int woff, int value) {
if (bigEndian()) {
write(woff, value >>> 8);
write(woff + 1, value & 0xFF);
@ -1520,7 +1520,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeMedium(int value) {
public Buffer writeMedium(int value) {
if (bigEndian()) {
write(value >>> 16);
write(value >>> 8 & 0xFF);
@ -1534,7 +1534,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf setMedium(int woff, int value) {
public Buffer setMedium(int woff, int value) {
if (bigEndian()) {
write(woff, value >>> 16);
write(woff + 1, value >>> 8 & 0xFF);
@ -1548,7 +1548,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeUnsignedMedium(int value) {
public Buffer writeUnsignedMedium(int value) {
if (bigEndian()) {
write(value >>> 16);
write(value >>> 8 & 0xFF);
@ -1562,7 +1562,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf setUnsignedMedium(int woff, int value) {
public Buffer setUnsignedMedium(int woff, int value) {
if (bigEndian()) {
write(woff, value >>> 16);
write(woff + 1, value >>> 8 & 0xFF);
@ -1612,7 +1612,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeInt(int value) {
public Buffer writeInt(int value) {
if (bigEndian()) {
write(value >>> 24);
write(value >>> 16 & 0xFF);
@ -1628,7 +1628,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf setInt(int woff, int value) {
public Buffer setInt(int woff, int value) {
if (bigEndian()) {
write(woff, value >>> 24);
write(woff + 1, value >>> 16 & 0xFF);
@ -1644,7 +1644,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeUnsignedInt(long value) {
public Buffer writeUnsignedInt(long value) {
if (bigEndian()) {
write((int) (value >>> 24));
write((int) (value >>> 16 & 0xFF));
@ -1660,7 +1660,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf setUnsignedInt(int woff, long value) {
public Buffer setUnsignedInt(int woff, long value) {
if (bigEndian()) {
write(woff, (int) (value >>> 24));
write(woff + 1, (int) (value >>> 16 & 0xFF));
@ -1686,12 +1686,12 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeFloat(float value) {
public Buffer writeFloat(float value) {
return writeUnsignedInt(Float.floatToRawIntBits(value));
}
@Override
public Buf setFloat(int woff, float value) {
public Buffer setFloat(int woff, float value) {
return setUnsignedInt(woff, Float.floatToRawIntBits(value));
}
@ -1718,7 +1718,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeLong(long value) {
public Buffer writeLong(long value) {
if (bigEndian()) {
write((int) (value >>> 56));
write((int) (value >>> 48 & 0xFF));
@ -1742,7 +1742,7 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf setLong(int woff, long value) {
public Buffer setLong(int woff, long value) {
if (bigEndian()) {
write(woff, (int) (value >>> 56));
write(woff + 1, (int) (value >>> 48 & 0xFF));
@ -1776,12 +1776,12 @@ final class CompositeBuf extends RcSupport<Buf, CompositeBuf> implements Buf {
}
@Override
public Buf writeDouble(double value) {
public Buffer writeDouble(double value) {
return writeLong(Double.doubleToRawLongBits(value));
}
@Override
public Buf setDouble(int woff, double value) {
public Buffer setDouble(int woff, double 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;
class ManagedAllocator implements Allocator, AllocatorControl {
class ManagedBufferAllocator implements BufferAllocator, AllocatorControl {
private final MemoryManager manager;
private final Cleaner cleaner;
ManagedAllocator(MemoryManager manager, Cleaner cleaner) {
ManagedBufferAllocator(MemoryManager manager, Cleaner cleaner) {
this.manager = manager;
this.cleaner = cleaner;
}
@Override
public Buf allocate(int size) {
Allocator.checkSize(size);
public Buffer allocate(int size) {
BufferAllocator.checkSize(size);
return manager.allocateShared(this, size, manager.drop(), cleaner);
}
@Override
public Object allocateUntethered(Buf originator, int size) {
Allocator.checkSize(size);
public Object allocateUntethered(Buffer originator, int size) {
BufferAllocator.checkSize(size);
var buf = manager.allocateShared(this, size, NO_OP_DROP, null);
return manager.unwrapRecoverableMemory(buf);
}

View File

@ -30,9 +30,9 @@ public interface MemoryManager {
}
boolean isNative();
Buf allocateConfined(AllocatorControl alloc, long size, Drop<Buf> drop, Cleaner cleaner);
Buf allocateShared(AllocatorControl allo, long size, Drop<Buf> drop, Cleaner cleaner);
Drop<Buf> drop();
Object unwrapRecoverableMemory(Buf buf);
Buf recoverMemory(Object recoverableMemory, Drop<Buf> drop);
Buffer allocateConfined(AllocatorControl alloc, long size, Drop<Buffer> drop, Cleaner cleaner);
Buffer allocateShared(AllocatorControl allo, long size, Drop<Buffer> drop, Cleaner cleaner);
Drop<Buffer> drop();
Object unwrapRecoverableMemory(Buffer buf);
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 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(
lookup(), SizeClassedMemoryPool.class, "closed", boolean.class);
private final MemoryManager manager;
private final ConcurrentHashMap<Integer, ConcurrentLinkedQueue<Send<Buf>>> pool;
private final ConcurrentHashMap<Integer, ConcurrentLinkedQueue<Send<Buffer>>> pool;
@SuppressWarnings("unused")
private volatile boolean closed;
@ -38,10 +38,10 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
}
@Override
public Buf allocate(int size) {
Allocator.checkSize(size);
public Buffer allocate(int size) {
BufferAllocator.checkSize(size);
var sizeClassPool = getSizeClassPool(size);
Send<Buf> send = sizeClassPool.poll();
Send<Buffer> send = sizeClassPool.poll();
if (send != null) {
return send.receive()
.reset()
@ -56,13 +56,13 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
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);
drop.attach(buf);
return buf;
}
protected Drop<Buf> getDrop() {
protected Drop<Buffer> getDrop() {
return new CleanerPooledDrop(this, getMemoryManager(), this);
}
@ -71,7 +71,7 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
if (CLOSE.compareAndSet(this, false, true)) {
var capturedExceptions = new ArrayList<Exception>(4);
pool.forEach((k, v) -> {
Send<Buf> send;
Send<Buffer> send;
while ((send = v.poll()) != null) {
try {
send.receive().close();
@ -89,7 +89,7 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
}
@Override
public void drop(Buf buf) {
public void drop(Buffer buf) {
if (closed) {
dispose(buf);
return;
@ -97,7 +97,7 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
var sizeClassPool = getSizeClassPool(buf.capacity());
sizeClassPool.offer(buf.send());
if (closed) {
Send<Buf> send;
Send<Buffer> send;
while ((send = sizeClassPool.poll()) != null) {
send.receive().close();
}
@ -105,12 +105,12 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
}
@Override
public Object allocateUntethered(Buf originator, int size) {
public Object allocateUntethered(Buffer originator, int size) {
var sizeClassPool = getSizeClassPool(size);
Send<Buf> send = sizeClassPool.poll();
Buf untetheredBuf;
Send<Buffer> send = sizeClassPool.poll();
Buffer untetheredBuf;
if (send != null) {
var transfer = (TransferSend<Buf, Buf>) send;
var transfer = (TransferSend<Buffer, Buffer>) send;
var owned = transfer.unsafeUnwrapOwned();
untetheredBuf = owned.transferOwnership(NO_OP_DROP);
} else {
@ -127,11 +127,11 @@ class SizeClassedMemoryPool implements Allocator, AllocatorControl, Drop<Buf> {
buf.close();
}
private ConcurrentLinkedQueue<Send<Buf>> getSizeClassPool(int size) {
private ConcurrentLinkedQueue<Send<Buffer>> getSizeClassPool(int size) {
return pool.computeIfAbsent(size, k -> new ConcurrentLinkedQueue<>());
}
private void dispose(Buf buf) {
private void dispose(Buffer buf) {
manager.drop().drop(buf);
}
}

View File

@ -21,7 +21,7 @@ import java.lang.ref.Cleaner;
interface Statics {
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) {

View File

@ -16,10 +16,10 @@
package io.netty.buffer.api.memseg;
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.MemoryManager;
import io.netty.buffer.api.memseg.MemSegBuf.RecoverableMemory;
import io.netty.buffer.api.memseg.MemSegBuffer.RecoverableMemory;
import jdk.incubator.foreign.MemorySegment;
import java.lang.ref.Cleaner;
@ -29,38 +29,38 @@ public abstract class AbstractMemorySegmentManager implements MemoryManager {
public abstract boolean isNative();
@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);
if (cleaner != null) {
segment = segment.registerCleaner(cleaner);
}
return new MemSegBuf(segment, convert(drop), alloc);
return new MemSegBuffer(segment, convert(drop), alloc);
}
@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();
if (cleaner != null) {
segment = segment.registerCleaner(cleaner);
}
return new MemSegBuf(segment, convert(drop), alloc);
return new MemSegBuffer(segment, convert(drop), alloc);
}
protected abstract MemorySegment createSegment(long size);
@Override
public Drop<Buf> drop() {
return convert(MemSegBuf.SEGMENT_CLOSE);
public Drop<Buffer> drop() {
return convert(MemSegBuffer.SEGMENT_CLOSE);
}
@Override
public Object unwrapRecoverableMemory(Buf buf) {
var b = (MemSegBuf) buf;
public Object unwrapRecoverableMemory(Buffer buf) {
var b = (MemSegBuffer) buf;
return b.recoverableMemory();
}
@Override
public Buf recoverMemory(Object recoverableMemory, Drop<Buf> drop) {
public Buffer recoverMemory(Object recoverableMemory, Drop<Buffer> drop) {
var recovery = (RecoverableMemory) recoverableMemory;
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.VarHandle;
class BifurcatedDrop implements Drop<MemSegBuf> {
class BifurcatedDrop implements Drop<MemSegBuffer> {
private static final VarHandle COUNT;
static {
try {
@ -30,12 +30,12 @@ class BifurcatedDrop implements Drop<MemSegBuf> {
}
}
private final MemSegBuf originalBuf;
private final Drop<MemSegBuf> delegate;
private final MemSegBuffer originalBuf;
private final Drop<MemSegBuffer> delegate;
@SuppressWarnings("FieldMayBeFinal")
private volatile int count;
BifurcatedDrop(MemSegBuf originalBuf, Drop<MemSegBuf> delegate) {
BifurcatedDrop(MemSegBuffer originalBuf, Drop<MemSegBuffer> delegate) {
this.originalBuf = originalBuf;
this.delegate = delegate;
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
public void drop(MemSegBuf buf) {
public void drop(MemSegBuffer buf) {
int c;
int n;
do {
@ -66,11 +66,11 @@ class BifurcatedDrop implements Drop<MemSegBuf> {
}
@Override
public void attach(MemSegBuf obj) {
public void attach(MemSegBuffer obj) {
delegate.attach(obj);
}
Drop<MemSegBuf> unwrap() {
Drop<MemSegBuffer> unwrap() {
return delegate;
}

View File

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

View File

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

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;

View File

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

View File

@ -19,23 +19,23 @@ import java.util.Arrays;
import java.util.EnumSet;
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 Supplier<Allocator> factory;
private final Supplier<BufferAllocator> factory;
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.factory = factory;
properties = EnumSet.copyOf(Arrays.asList(props));
}
public Allocator createAllocator() {
public BufferAllocator createAllocator() {
return factory.get();
}
@Override
public Allocator get() {
public BufferAllocator get() {
return factory.get();
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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