This is an automated email from the ASF dual-hosted git repository.
tabish121 pushed a commit to branch 1.x
in repository https://gitbox.apache.org/repos/asf/qpid-protonj2.git
The following commit(s) were added to refs/heads/1.x by this push:
new 98b64e01 PROTON-3005 Fixes and tests for some ProtonBuffer use cases
98b64e01 is described below
commit 98b64e0138d7696313704f95a8a86f2986968017
Author: Timothy Bish <[email protected]>
AuthorDate: Fri Nov 13 12:01:10 2026 -0500
PROTON-3005 Fixes and tests for some ProtonBuffer use cases
Multi-component composite buffers did not behave like a single buffer in
several places along with some other API consistency issues which can lead
to errors when mixing buffers usages.
- Buffer iteration, forward and reverse, lost its place when crossing a
second component boundary.
- indexOf searched beyond the given window and returned an index local to
a component instead of an index into the composite.
- Transfer of bytes to and from a channel exceeded the requested length
when the data spanned multiple components.
- Composing an array of buffers did not flatten nested composites.
- Composite buffer component accessor mishandles read and write offset
advance and loses sync with the parent compositie buffer
- Composite buffer compaction was not correctly recycling older already
read buffers when it should have.
- Check for close in more buffer APIs to ensure consistent exceptions
- Validate more cases of buffer growth via ensureWritable and fix some
edge cases where some allocations can be saved.
- Ensure that the default writeBytes for a ByteBuffer handles little
endian direct buffers correctly for completeness
Also cleans up some stale javadocs and fixes a few minor issues spotted
during tests such as not checking buffer closed in all some cases and
throwing null pointer exception when a more appropriate buffer error
should be thrown.
(cherry picked from commit 032794585fa603002695d5d1d465df5dca2462d6)
---
.../apache/qpid/protonj2/buffer/ProtonBuffer.java | 60 +-
.../protonj2/buffer/ProtonBufferComponent.java | 51 +-
.../qpid/protonj2/buffer/ProtonBufferUtils.java | 14 +-
.../buffer/impl/ProtonByteArrayBuffer.java | 92 ++-
.../buffer/impl/ProtonCompositeBufferImpl.java | 106 +--
.../buffer/netty/Netty4ToProtonBufferAdapter.java | 72 +-
.../protonj2/buffer/ProtonAbstractBufferTest.java | 652 ++++++++++++++-
.../buffer/impl/ProtonByteArrayBufferTest.java | 45 +
.../buffer/impl/ProtonCompositeBufferImplTest.java | 913 +++++++++++++++++++++
.../netty/Netty4ProtonBufferAdapterTest.java | 33 +-
10 files changed, 1903 insertions(+), 135 deletions(-)
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBuffer.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBuffer.java
index d9051672..02fc15c9 100644
--- a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBuffer.java
+++ b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBuffer.java
@@ -20,6 +20,7 @@ import static
org.apache.qpid.protonj2.buffer.ProtonBufferUtils.checkIsNotNegati
import java.io.IOException;
import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
@@ -96,6 +97,7 @@ public interface ProtonBuffer extends ProtonBufferAccessors,
Resource<ProtonBuff
*
* @return this buffer for use in chaining.
*
+ * @throws ProtonBufferClosedException if the buffer has been closed
* @throws IndexOutOfBoundsException if the value given is greater than
the write offset or negative.
*/
ProtonBuffer setReadOffset(int value);
@@ -108,7 +110,8 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
*
* @return this ProtonBuffer for chaining.
*
- * @throws IllegalArgumentException if the {#code length} given is
negative.
+ * @throws ProtonBufferClosedException if the buffer has been closed
+ * @throws IllegalArgumentException if the {@code length} given is
negative.
* @throws IndexOutOfBoundsException
* if {@code length} is greater than {@code this.readableBytes}
*/
@@ -144,6 +147,8 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
*
* @return this buffer for use in chaining.
*
+ * @throws ProtonBufferReadOnlyException if the buffer is a read-only
buffer
+ * @throws ProtonBufferClosedException if the buffer has been closed
* @throws IndexOutOfBoundsException if the value less than the read
offset or greater than the capacity.
*/
ProtonBuffer setWriteOffset(int value);
@@ -156,7 +161,9 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
*
* @return this ProtonBuffer for chaining.
*
- * @throws IllegalArgumentException if the {#code length} given is
negative.
+ * @throws ProtonBufferClosedException if the buffer has been closed
+ * @throws ProtonBufferReadOnlyException if the buffer is a read-only
buffer
+ * @throws IllegalArgumentException if the {@code length} given is
negative.
* @throws IndexOutOfBoundsException
* if {@code length} is greater than the buffer {@link #capacity()}
*/
@@ -239,6 +246,8 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
*
* @return this buffer for using in call chaining.
*
+ * @throws ProtonBufferClosedException if the buffer has been closed
+ * @throws ProtonBufferReadOnlyException if the buffer is a read-only
buffer
* @throws IllegalArgumentException if the amount given is less than zero.
* @throws IndexOutOfBoundsException if the amount given would result in
the buffer
* exceeding the maximum capacity for this buffer.
@@ -271,6 +280,8 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
*
* @return this buffer for using in call chaining.
*
+ * @throws ProtonBufferClosedException if the buffer has been closed
+ * @throws ProtonBufferReadOnlyException if the buffer is a read-only
buffer
* @throws IllegalArgumentException if the amount given is less than zero.
* @throws IndexOutOfBoundsException if the amount given would result in
the buffer
* exceeding the maximum capacity for this buffer.
@@ -369,11 +380,15 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
* a buffer expansion would occur via an {@link #ensureWritable(int)} call.
*
* @return this buffer for using in call chaining.
+ *
+ * @throws ProtonBufferClosedException if the buffer has been closed
+ * @throws ProtonBufferReadOnlyException if the buffer is a read-only
buffer
*/
ProtonBuffer compact();
/**
- * Splits this buffer at the read offset + the length given.
+ * Splits this buffer at the read offset + the length given and returns a
new
+ * buffer that contains the bytes that came before the indicated split
point
*
* @param length
* The number of bytes beyond the read offset where the
split should occur
@@ -385,7 +400,8 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
}
/**
- * Splits this buffer at the write offset + the length given.
+ * Splits this buffer at the write offset + the length given and returns a
new
+ * buffer that contains the bytes that came before the indicated split
point
*
* @param length
* The number of bytes beyond the write offset where the
split should occur
@@ -397,7 +413,8 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
}
/**
- * Splits this buffer at the write offset.
+ * Splits this buffer at the write offset and returns a new buffer that
contains the
+ * bytes that came before the current write offset.
* <p>
* This creates two independent buffers that can manage differing views of
the same
* memory region or in the case of a composite buffer two buffers that
take ownership
@@ -415,7 +432,8 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
}
/**
- * Splits this buffer at the given offset.
+ * Splits this buffer at the given offset and returns a new buffer that
contains
+ * the bytes that came before the split offset.
* <p>
* This creates two independent buffers that can manage differing views of
the same
* memory region or in the case of a composite buffer two buffers that
take ownership
@@ -434,13 +452,16 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
ProtonBuffer split(int splitOffset);
/**
- * Returns a String created from the buffer's underlying bytes using the
specified
+ * Returns a String created from the buffer's underlying readable bytes
using the specified
* {@link java.nio.charset.Charset} for the newly created String.
*
* @param charset
* the {@link java.nio.charset.Charset} to use to construct the new
string.
*
- * @return a string created from the buffer's underlying bytes using the
given {@link java.nio.charset.Charset}.
+ * @return a string created from the buffer's underlying readable bytes
using the given
+ * {@link java.nio.charset.Charset}.
+ *
+ * @throws ProtonBufferClosedException if the buffer has already been
closed
*/
default String toString(Charset charset) {
return ProtonBufferUtils.toString(this, charset);
@@ -459,6 +480,9 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
* or greater than the given buffer.
*
* @see Comparable#compareTo(Object)
+ *
+ * @throws NullPointerException if the passed buffer is null
+ * @throws ProtonBufferClosedException if either this buffer or the passed
in buffer has been closed
*/
@Override
default int compareTo(ProtonBuffer buffer) {
@@ -643,13 +667,19 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
}
advanceWriteOffset(source.remaining());
- // Try to reduce bounds-checking by using larger primitives when
possible.
- for (; length >= Long.BYTES; length -= Long.BYTES, writeOffset +=
Long.BYTES) {
- setLong(writeOffset, source.getLong());
- }
- for (; length >= Integer.BYTES; length -= Integer.BYTES,
writeOffset += Integer.BYTES) {
- setInt(writeOffset, source.getInt());
+ // Try to reduce bounds-checking by using larger primitives when
possible based on the
+ // size of the buffer and its byte order.
+ if (source.order() == ByteOrder.BIG_ENDIAN) {
+ for (; length >= Long.BYTES; length -= Long.BYTES, writeOffset
+= Long.BYTES) {
+ setLong(writeOffset, source.getLong());
+ }
+ for (; length >= Integer.BYTES; length -= Integer.BYTES,
writeOffset += Integer.BYTES) {
+ setInt(writeOffset, source.getInt());
+ }
}
+
+ // We either handle any bytes that the above copy could not
complete or we handle all
+ // byte copies if the source direct buffer is not in BIG_ENDIAN
byte order.
for (; length > 0; length--, writeOffset++) {
setByte(writeOffset, source.get());
}
@@ -894,7 +924,7 @@ public interface ProtonBuffer extends
ProtonBufferAccessors, Resource<ProtonBuff
* @param offset
* The offset into the buffer where the search should
begin from.
* @param length
- * The offset into the buffer where the search should
begin from.
+ * The number of bytes to search beyond the given offset.
*
* @return the location in the buffer where the value was found or
<code>-1</code> if not found.
*/
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBufferComponent.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBufferComponent.java
index 2e095c9b..8d71c473 100644
---
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBufferComponent.java
+++
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBufferComponent.java
@@ -36,8 +36,8 @@ public interface ProtonBufferComponent {
Object unwrap();
/**
- * Returns the number of readable bytes in the buffer safely regards of
- * the actual memory backing this component.
+ * Returns the number of readable bytes in the buffer regardless of the
+ * actual memory backing this component.
*
* @return the number of readable bytes in this buffer component
*/
@@ -58,7 +58,9 @@ public interface ProtonBufferComponent {
*
* @return this {@link ProtonBufferComponent} instance.
*
- * @throws UnsupportedOperationException if the component is not backed by
a readable array.
+ * @throws ProtonBufferClosedException if the buffer is closed
+ * @throws IndexOutOfBoundsException if the request results in an advance
that violates the component boundaries.
+ * @throws IllegalArgumentException if the given amount is negative
*/
ProtonBufferComponent advanceReadOffset(int amount);
@@ -67,36 +69,35 @@ public interface ProtonBufferComponent {
*
* @return the readable array that backs this buffer component.
*
+ * @throws ProtonBufferClosedException if the buffer is closed
* @throws UnsupportedOperationException if the component is not backed by
an array or has no readable bytes.
*/
byte[] getReadableArray();
/**
- * @return the offset into the readable array where the readable bytes
begin.
- *
- * @throws UnsupportedOperationException if the component is not backed by
a readable array.
+ * @return the offset into the readable array where the readable bytes
begin, or zero when
+ * {@link #hasReadbleArray()} is false.
*/
int getReadableArrayOffset();
/**
- * @return the length of the readable array from the offset that is owned
by this component..
- *
- * @throws UnsupportedOperationException if the component is not backed by
a readable array.
+ * @return the length of the readable array from the offset that is owned
by this component, or
+ * zero when {@link #hasReadbleArray()} is false.
*/
int getReadableArrayLength();
/**
- * Returns the readable array if one exists or throws an exception.
+ * Returns a {@link ByteBuffer} that covers the readable bytes of this
component.
*
- * @return the readable array that backs this buffer component.
+ * @return the readable buffer that backs this buffer component.
*
- * @throws UnsupportedOperationException if the component does not contain
a readable portion.
+ * @throws ProtonBufferClosedException if the buffer is closed
*/
ByteBuffer getReadableBuffer();
/**
- * Returns the number of writable bytes in the buffer safely regards of
- * the actual memory backing this component.
+ * Returns the number of writable bytes in the buffer regardless of the
+ * actual memory backing this component.
*
* @return the number of writable bytes in this buffer component
*/
@@ -112,7 +113,10 @@ public interface ProtonBufferComponent {
*
* @return this {@link ProtonBufferComponent} instance.
*
- * @throws UnsupportedOperationException if the component is not backed by
a writable array.
+ * @throws ProtonBufferReadOnlyException if the buffer is a read-only
buffer
+ * @throws ProtonBufferClosedException if the buffer is closed
+ * @throws IndexOutOfBoundsException if the request results in an advance
that violates the component boundaries
+ * @throws IllegalArgumentException if the given amount is negative
*/
ProtonBufferComponent advanceWriteOffset(int amount);
@@ -126,30 +130,29 @@ public interface ProtonBufferComponent {
*
* @return the writable array that backs this buffer component.
*
- * @throws UnsupportedOperationException if the component is not backed by
an writable array.
+ * @throws ProtonBufferClosedException if the buffer is closed
+ * @throws UnsupportedOperationException if the component is not backed by
an array or has no writable bytes.
*/
byte[] getWritableArray();
/**
- * @return the offset into the writable array where the writable bytes
begin.
- *
- * @throws UnsupportedOperationException if the component is not backed by
a writable array.
+ * @return the offset into the writable array where the writable bytes
begin, or zero when
+ * {@link #hasWritableArray()} is false.
*/
int getWritableArrayOffset();
/**
- * @return the length of the writable array from the offset that is owned
by this component..
- *
- * @throws UnsupportedOperationException if the component is not backed by
a writable array.
+ * @return the length of the writable array from the offset that is owned
by this component, or
+ * zero when {@link #hasWritableArray()} is false.
*/
int getWritableArrayLength();
/**
- * Returns the writable {@link ByteBuffer} if one exists or throws an
exception.
+ * Returns a {@link ByteBuffer} that covers the writable bytes of this
component.
*
* @return the writable buffer that backs this buffer component.
*
- * @throws UnsupportedOperationException if the component does not contain
a writable portion.
+ * @throws ProtonBufferClosedException if the buffer is closed
*/
ByteBuffer getWritableBuffer();
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBufferUtils.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBufferUtils.java
index 1d8f5a38..90aa4d6b 100644
---
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBufferUtils.java
+++
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/ProtonBufferUtils.java
@@ -104,8 +104,11 @@ public abstract class ProtonBufferUtils {
* @return a {@link String} that is a view of the given buffer's readable
bytes.
*/
public static String toString(ProtonBuffer buffer, Charset charset) {
- byte[] copy = new byte[buffer.getReadableBytes()];
+ ProtonBufferUtils.checkIsClosed(buffer);
+ final byte[] copy = new byte[buffer.getReadableBytes()];
+
buffer.copyInto(buffer.getReadOffset(), copy, 0, copy.length);
+
return new String(copy, 0, copy.length, charset);
}
@@ -878,8 +881,17 @@ public abstract class ProtonBufferUtils {
* The right hand side buffer to compare.
*
* @return the value 0 if {@code x == y}; a value less than 0 if {@code x
< y}; and a value greater than 0 if {@code x > y}.
+ *
+ * @throws NullPointerException if either passed buffer is null
+ * @throws ProtonBufferClosedException if either passed buffer is closed
*/
public static int compare(ProtonBuffer lhs, ProtonBuffer rhs) {
+ Objects.requireNonNull(lhs, "The left hand buffer cannot be null");
+ Objects.requireNonNull(rhs, "The right hand buffer cannot be null");
+
+ checkIsClosed(lhs);
+ checkIsClosed(rhs);
+
int length = lhs.getReadOffset() + Math.min(lhs.getReadableBytes(),
rhs.getReadableBytes());
for (int i = lhs.getReadOffset(), j = rhs.getReadOffset(); i < length;
i++, j++) {
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/impl/ProtonByteArrayBuffer.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/impl/ProtonByteArrayBuffer.java
index 7424bf69..5ab8b17b 100644
---
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/impl/ProtonByteArrayBuffer.java
+++
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/impl/ProtonByteArrayBuffer.java
@@ -61,7 +61,7 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
private int arrayOffset;
/**
- * Tracks the readable capacity of this buffer. This value is calculated
based on
+ * Tracks the readable capacity of this buffer. This value is calculated
based on
* the given target array and the offset value at create time plus any
create time
* restriction that limits the usable sub-region of the array to less than
the total
* length minus the offset
@@ -69,7 +69,7 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
private int readCapacity;
/**
- * Tracks the read capacity for buffers that are both readable and
writable and is
+ * Tracks the write capacity for buffers that are both readable and
writable and is
* set to the closed state for a buffer than has been made read only.
*/
private int writeCapacity;
@@ -170,6 +170,9 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
* The offset into the backing array where the buffer
starts.
* @param implicitGrowthLimit
* The maximum to which this buffer can grow implicitly (without
calls to ensureWritable).
+ *
+ * @throws IndexOutOfBoundsException if {@code arrayOffset} is negative or
exceeds the length of the backing array
+ * @throws IllegalArgumentException if {@code implicitGrowthLimit} is
negative
*/
public ProtonByteArrayBuffer(byte[] backingArray, int arrayOffset, int
implicitGrowthLimit) {
this(backingArray, arrayOffset, backingArray.length - arrayOffset,
implicitGrowthLimit);
@@ -179,6 +182,10 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
* Create a new proton byte buffer instance with given backing array as the
* starting backing store and uses the provided max capacity value to
control
* how large the buffer could ever grow.
+ * <p>
+ * If the implicit growth limit is set less than or equal to capacity the
buffer
+ * implicit growth feature is disabled and users must call {@link
#ensureWritable(int)}
+ * to increase the buffer capacity.
*
* @param backingArray
* The byte array that will back the buffer instance
@@ -188,8 +195,24 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
* The capacity limit for this view of the provided backing array.
* @param implicitGrowthLimit
* The maximum to which this buffer can grow implicitly (without
calls to ensureWritable).
+ *
+ * @throws IndexOutOfBoundsException if {@code arrayOffset} or {@code
capacity} is negative, or if the span
+ * {@code arrayOffset + capacity} extends beyond the end of the
backing array
+ * @throws IllegalArgumentException if {@code implicitGrowthLimit} is
negative
*/
public ProtonByteArrayBuffer(byte[] backingArray, int arrayOffset, int
capacity, int implicitGrowthLimit) {
+ if (arrayOffset < 0) {
+ throw new IndexOutOfBoundsException("Array offset cannot be
assigned as a negative number");
+ }
+
+ if (capacity < 0) {
+ throw new IndexOutOfBoundsException("Buffer capacity cannot be
assigned as a negative number");
+ }
+
+ if (implicitGrowthLimit < 0) {
+ throw new IllegalArgumentException("Buffer implicit growth limit
cannot be assigned as a negative number");
+ }
+
if (arrayOffset > backingArray.length) {
throw new IndexOutOfBoundsException("Array offset cannot exceed
the array length");
}
@@ -516,7 +539,7 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
final ProtonByteArrayBuffer result;
if (readOnly && isReadOnly()) {
- result = new ProtonByteArrayBuffer(array, offset(offset), length,
implicitGrowthLimit);
+ result = new ProtonByteArrayBuffer(array, offset(offset), length,
ProtonBufferUtils.MAX_BUFFER_CAPACITY);
result.writeOffset = length;
} else {
checkGet(offset, length);
@@ -643,7 +666,7 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
if (writeCapacity == CLOSED_MARKER) {
throw ProtonBufferUtils.genericBufferIsReadOnly(this);
}
- if (getWritableBytes() > size) {
+ if (getWritableBytes() >= size) {
return this;
}
if (allowCompaction && getWritableBytes() + getReadOffset() >= size) {
@@ -701,8 +724,8 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
return 0;
}
- final ByteBuffer ioWrapper = ByteBuffer.wrap(array, readOffset,
writableBytes);
- final int actualWrite = channel.write(ioWrapper);
+ final ByteBuffer ioWrapper = ByteBuffer.wrap(array, arrayOffset +
readOffset, writableBytes);
+ final int actualWrite = channel.write(ioWrapper.slice());
readOffset += actualWrite;
return actualWrite;
@@ -822,22 +845,42 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
@Override
public byte[] getReadableArray() {
- return array;
+ ProtonBufferUtils.checkIsClosed(this);
+
+ if (hasReadbleArray()) {
+ return array;
+ } else {
+ throw new UnsupportedOperationException("The buffer does not have
a readable array");
+ }
}
@Override
public int getReadableArrayOffset() {
- return arrayOffset + readOffset;
+ if (hasReadbleArray()) {
+ return arrayOffset + readOffset;
+ } else {
+ return 0;
+ }
}
@Override
public int getReadableArrayLength() {
- return writeOffset - readOffset;
+ if (hasReadbleArray()) {
+ return getReadableBytes();
+ } else {
+ return 0;
+ }
}
@Override
public ByteBuffer getReadableBuffer() {
- return ByteBuffer.wrap(array, arrayOffset + readOffset, readCapacity -
readOffset).asReadOnlyBuffer();
+ ProtonBufferUtils.checkIsClosed(this);
+
+ if (getReadableBytes() <= 0) {
+ return ByteBuffer.allocate(0).asReadOnlyBuffer();
+ } else {
+ return ByteBuffer.wrap(array, getReadableArrayOffset(),
getReadableArrayLength()).asReadOnlyBuffer();
+ }
}
@Override
@@ -847,30 +890,46 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
@Override
public boolean hasWritableArray() {
- return writeCapacity > 0;
+ return !isReadOnly() && isWritable();
}
@Override
public byte[] getWritableArray() {
- return array;
+ ProtonBufferUtils.checkIsClosed(this);
+
+ if (hasWritableArray()) {
+ return array;
+ } else {
+ throw new UnsupportedOperationException("The buffer does not have
a writable array");
+ }
}
@Override
public int getWritableArrayOffset() {
- return arrayOffset + writeOffset;
+ if (hasWritableArray()) {
+ return arrayOffset + writeOffset;
+ } else {
+ return 0;
+ }
}
@Override
public int getWritableArrayLength() {
- return getWritableBytes();
+ if (hasWritableArray()) {
+ return getWritableBytes();
+ } else {
+ return 0;
+ }
}
@Override
public ByteBuffer getWritableBuffer() {
+ ProtonBufferUtils.checkIsClosed(this);
+
if (writeCapacity < 0) {
return ByteBuffer.allocate(0);
} else {
- return ByteBuffer.wrap(array, arrayOffset + writeOffset,
getWritableBytes());
+ return ByteBuffer.wrap(array, getWritableArrayOffset(),
getWritableBytes());
}
}
@@ -950,6 +1009,7 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
transfer.writeCapacity = writeCapacity;
transfer.readOffset = readOffset;
transfer.writeOffset = writeOffset;
+ transfer.implicitGrowthLimit = implicitGrowthLimit;
return transfer;
}
@@ -1026,7 +1086,7 @@ public final class ProtonByteArrayBuffer extends
SharedResource<ProtonBuffer> im
int capacity = capacity();
if (mayExpand && index >= 0 && index <= capacity && writeOffset + size
<= implicitGrowthLimit) {
- int minimumGrowth = Math.min(Math.max(capacity * 2, size),
implicitGrowthLimit) - capacity;
+ final int minimumGrowth = Math.min(Math.max(capacity, size),
implicitGrowthLimit - capacity);
ensureWritable(size, minimumGrowth, false);
checkSet(index, size); // Verify writing is now possible, without
recursing.
return;
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/impl/ProtonCompositeBufferImpl.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/impl/ProtonCompositeBufferImpl.java
index b2ad5259..34d5e276 100644
---
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/impl/ProtonCompositeBufferImpl.java
+++
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/impl/ProtonCompositeBufferImpl.java
@@ -131,6 +131,7 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
this.readOffset = other.readOffset;
this.writeOffset = other.writeOffset;
this.lastAccessedChunk = other.lastAccessedChunk;
+ this.implicitGrowthLimit = other.implicitGrowthLimit;
}
/**
@@ -182,7 +183,7 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
@Override
public ProtonCompositeBuffer fill(byte value) {
ProtonBufferUtils.checkIsClosed(this);
- checkWriteBounds(value, 0);
+ checkWriteBounds(0, 1);
for (int i = 0; i < buffers.length; ++i) {
buffers[i].fill(value);
@@ -566,7 +567,12 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
return this;
}
- if (allowCompaction && readOffset >= size) {
+ // Read offset needs to be greater than or equal to whatever portion
of the size we can't
+ // already accommodate otherwise we assume it to be more efficient to
just allocate a new buffer.
+ //
+ // NOTE: we could still attempt to reclaim any read buffers to reduce
the allocation amount
+ // but that might result in a higher sunk time cost.
+ if (allowCompaction && readOffset >= (size - getWritableBytes())) {
if (buffers.length == 1) {
final ProtonBuffer target = buffers[0];
target.compact();
@@ -576,7 +582,7 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
int compacted = 0;
for (int i = 0; i < buffers.length; ++i) {
final ProtonBuffer current = buffers[i];
- if (current.getReadableBytes() == current.capacity()) {
+ if (current.getReadOffset() == current.capacity()) {
compacted++;
// Buffer is now fully writable so reset the offsets
current.clear();
@@ -594,7 +600,14 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
// Move the rest down
System.arraycopy(buffers, compacted, buffers, 0,
buffers.length - compacted);
// Placed the compacted buffers at the tail
- System.arraycopy(compactedSet, 0, buffers, compacted,
compacted);
+ System.arraycopy(compactedSet, 0, buffers, buffers.length
- compacted, compacted);
+
+ // Update read offset and write offset to account for
removing the
+ // set of buffers from the front
+ for (ProtonBuffer compactedBuffer : compactedSet) {
+ readOffset -= compactedBuffer.capacity();
+ writeOffset -= compactedBuffer.capacity();
+ }
recomputeChunkIndexValues();
}
@@ -979,7 +992,7 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
while (bytesWritten < length && currentChunkIndex < buffers.length) {
final ProtonBuffer buffer = buffers[currentChunkIndex];
- final int chunkedWrite = Math.min(buffer.getReadableBytes(),
length);
+ final int chunkedWrite = Math.min(buffer.getReadableBytes(),
length - bytesWritten);
final int written = buffer.transferTo(channel, chunkedWrite);
@@ -1001,21 +1014,21 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
ProtonBufferUtils.checkIsClosed(this);
ProtonBufferUtils.checkIsReadOnly(this);
- final int readableBytes = Math.min(getWritableBytes(), length);
+ final int bytesToRead = Math.min(getWritableBytes(), length);
- if (readableBytes == 0) {
+ if (bytesToRead == 0) {
return 0;
}
- checkWriteBounds(getWriteOffset(), readableBytes);
+ checkWriteBounds(getWriteOffset(), bytesToRead);
int lastAccessedChunk = findChunkWithIndex(writeOffset);
int bytesRead = 0;
- while (bytesRead < readableBytes && lastAccessedChunk <
buffers.length) {
+ while (bytesRead < bytesToRead && lastAccessedChunk < buffers.length) {
final ProtonBuffer buffer = buffers[lastAccessedChunk];
- final int chunckedRead = Math.min(buffer.getWritableBytes(),
readableBytes);
+ final int chunckedRead = Math.min(buffer.getWritableBytes(),
bytesToRead - bytesRead);
final int read = buffer.transferFrom(channel, chunckedRead);
@@ -1039,21 +1052,21 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
ProtonBufferUtils.checkIsClosed(this);
ProtonBufferUtils.checkIsReadOnly(this);
- final int readableBytes = Math.min(getWritableBytes(), length);
+ final int bytesToRead = Math.min(getWritableBytes(), length);
- if (readableBytes == 0) {
+ if (bytesToRead == 0) {
return 0;
}
- checkWriteBounds(getWriteOffset(), readableBytes);
+ checkWriteBounds(getWriteOffset(), bytesToRead);
int lastAccessedChunk = findChunkWithIndex(writeOffset);
int bytesRead = 0;
- while (bytesRead < readableBytes && lastAccessedChunk <
buffers.length) {
+ while (bytesRead < bytesToRead && lastAccessedChunk < buffers.length) {
final ProtonBuffer buffer = buffers[lastAccessedChunk];
- final int chunckedRead = Math.min(buffer.getWritableBytes(),
readableBytes);
+ final int chunckedRead = Math.min(buffer.getWritableBytes(),
bytesToRead - bytesRead);
final int read = buffer.transferFrom(channel, position,
chunckedRead);
@@ -1116,7 +1129,7 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
final byte result =
buffers[currentBufferIndex].getByte(currentBufferOffset++);
if (++offset != endOffset && currentBufferOffset ==
buffers[currentBufferIndex].capacity()) {
- currentBufferIndex = findChunkWithIndex(currentBufferOffset);
+ currentBufferIndex++;
currentBufferOffset = 0;
}
@@ -1182,8 +1195,7 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
final byte result =
buffers[currentBufferIndex].getByte(currentBufferOffset--);
if (--offset != endOffset && currentBufferOffset < 0) {
- currentBufferIndex = findChunkWithIndex(offset);
- currentBufferOffset = 0;
+ currentBufferOffset = buffers[--currentBufferIndex].capacity()
- 1;
}
return result;
@@ -1208,22 +1220,25 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
checkIndexOfBounds(offset, length);
- int bytesRead = 0;
+ if (length == 0) {
+ return -1;
+ }
+
int lastAccessedChunk = findChunkWithIndex(offset);
int readOffset = offset - startIndices[lastAccessedChunk];
while (length > 0 && lastAccessedChunk != buffers.length) {
- final ProtonBuffer buffer = buffers[lastAccessedChunk++];
- final int readableBytes = Math.min(buffer.capacity(), length);
+ final ProtonBuffer buffer = buffers[lastAccessedChunk];
+ final int readableBytes = Math.min(buffer.capacity() - readOffset,
length);
final int result = buffer.indexOf(needle, readOffset,
readableBytes);
if (result != -1) {
- return bytesRead + result;
+ return startIndices[lastAccessedChunk] + result;
}
- bytesRead += buffer.getReadableBytes();
- length -= buffer.getReadableBytes();
+ length -= readableBytes;
readOffset = 0;
+ lastAccessedChunk++;
}
return -1;
@@ -1268,6 +1283,10 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
public static ProtonCompositeBuffer create(ProtonBufferAllocator
allocator, ProtonBuffer[] buffers) {
Objects.requireNonNull(buffers, "Provided buffers array cannot be
null");
+ if (buffers.length == 0) {
+ return new ProtonCompositeBufferImpl(allocator);
+ }
+
final boolean readOnly = buffers[0].isReadOnly();
final ProtonBuffer[] chain =
buildChainFromBuffers(Arrays.copyOf(buffers, buffers.length));
final ProtonCompositeBuffer result;
@@ -1367,32 +1386,31 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
// Claim each buffer before proceeding to filter and trim the buffers
for composition.
// Decompose and composites here before moving on to the next phase as
well as removing
// any zero capacity buffers.
- for (int i = 0; i < chain.length; i++) {
+ for (int i = 0; i < buffers.length; i++) {
+ final ProtonBuffer current = buffers[i];
+
try {
- if (buffers[i].capacity() > 0) {
- if (buffers[i].isComposite()) {
- final int bufferCount = buffers[i].componentCount();
+ if (current.capacity() > 0) {
+ if (current.isComposite()) {
+ final int bufferCount = current.componentCount();
if (bufferCount > 1) {
chain = Arrays.copyOf(chain, chain.length +
bufferCount - 1);
}
- for (ProtonBuffer buffer :
((ProtonCompositeBuffer)buffers[i]).decomposeBuffer()) {
+ for (ProtonBuffer buffer :
((ProtonCompositeBuffer)current).decomposeBuffer()) {
chain[totalChunks++] = buffer;
}
- i += bufferCount - 1;
-
continue;
} else {
- chain[i] = buffers[i].transfer();
- totalChunks++;
+ chain[totalChunks++] = current.transfer();
}
- } else if (buffers[i].isClosed()) {
+ } else if (current.isClosed()) {
// This will capture attempt to add duplicate
throw new ProtonBufferClosedException("Cannot create a
composite from a closed buffer");
} else {
- buffers[i].close();
+ current.close();
}
} catch (RuntimeException e) {
suppressed = e;
@@ -1836,27 +1854,27 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
@Override
public byte peekByte() {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("Internal only buffer
accessor which does not support this operation");
}
@Override
public byte getByte(int index) {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("Internal only buffer
accessor which does not support this operation");
}
@Override
public ProtonBuffer setByte(int index, byte value) {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("Internal only buffer
accessor which does not support this operation");
}
@Override
public byte readByte() {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("Internal only buffer
accessor which does not support this operation");
}
@Override
public ProtonBuffer writeByte(byte value) {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("Internal only buffer
accessor which does not support this operation");
}
@Override
@@ -2101,8 +2119,6 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
private ProtonBufferComponent currentComponent;
private int bufferIndex;
- private int cumulativeReadSkip; // Track total read skip to update
parent in-place
- private int cumulativeWriteSkip; // Track total read skip to update
parent in-place
public
ProtonCompositeBufferComponentAccessor(ProtonCompositeBufferImpl composite) {
this.composite = composite;
@@ -2168,8 +2184,7 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
@Override
public ProtonBufferComponent advanceReadOffset(int amount) {
currentComponent.advanceReadOffset(amount);
- composite.setReadOffset(cumulativeReadSkip + amount);
- cumulativeReadSkip += amount;
+ composite.setReadOffset(composite.getReadOffset() + amount);
return currentComponent;
}
@@ -2202,8 +2217,7 @@ public final class ProtonCompositeBufferImpl extends
SharedResource<ProtonBuffer
@Override
public ProtonBufferComponent advanceWriteOffset(int amount) {
currentComponent.advanceWriteOffset(amount);
- composite.setWriteOffset(cumulativeWriteSkip + amount);
- cumulativeWriteSkip += amount;
+ composite.setWriteOffset(composite.getWriteOffset() + amount);
return currentComponent;
}
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/netty/Netty4ToProtonBufferAdapter.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/netty/Netty4ToProtonBufferAdapter.java
index 4b407124..b9e05729 100644
---
a/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/netty/Netty4ToProtonBufferAdapter.java
+++
b/protonj2/src/main/java/org/apache/qpid/protonj2/buffer/netty/Netty4ToProtonBufferAdapter.java
@@ -106,10 +106,10 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
* The {@link ByteBuf} resource to wrap.
*/
public Netty4ToProtonBufferAdapter(Netty4ProtonBufferAllocator allocator,
ByteBuf resource) {
- this(allocator, resource, Objects.requireNonNull(resource, "The
provided ByteBuf instance cannot be null").isReadOnly());
+ this(allocator, resource, Objects.requireNonNull(resource, "The
provided ByteBuf instance cannot be null").isReadOnly(),
ProtonBufferUtils.MAX_BUFFER_CAPACITY);
}
- private Netty4ToProtonBufferAdapter(Netty4ProtonBufferAllocator allocator,
ByteBuf resource, boolean readOnly) {
+ private Netty4ToProtonBufferAdapter(Netty4ProtonBufferAllocator allocator,
ByteBuf resource, boolean readOnly, int implicitGrowthLimit) {
this.allocator = allocator;
this.resource = resource;
this.readOnly = readOnly;
@@ -117,6 +117,7 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
this.writeCapacity = readOnly ? CLOSED_MARKER : readCapacity;
this.readOffset = resource.readerIndex();
this.writeOffset = resource.writerIndex();
+ this.implicitGrowthLimit = implicitGrowthLimit;
}
public Netty4ProtonBufferAllocator allocator() {
@@ -484,7 +485,9 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
@Override
public String toString(Charset charset) {
- return resource.toString(charset);
+ ProtonBufferUtils.checkIsClosed(this);
+
+ return resource.toString(readOffset, getReadableBytes(), charset);
}
@Override
@@ -495,11 +498,6 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
", capacity: " + readCapacity + "}";
}
- @Override
- public int compareTo(ProtonBuffer buffer) {
- return ProtonBufferUtils.compare(this, buffer);
- }
-
@Override
public boolean equals(Object other) {
if (other instanceof ProtonBuffer) {
@@ -802,7 +800,7 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
@Override
public boolean hasReadbleArray() {
- return resource.hasArray();
+ return resource.hasArray() && isReadable();
}
@Override
@@ -812,21 +810,36 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
@Override
public byte[] getReadableArray() {
- return resource.array();
+ ProtonBufferUtils.checkIsClosed(this);
+
+ if (hasReadbleArray()) {
+ return resource.array();
+ } else {
+ throw new UnsupportedOperationException("The buffer does not have
a readable array");
+ }
}
@Override
public int getReadableArrayOffset() {
- return resource.arrayOffset() + getReadOffset();
+ if (hasReadbleArray()) {
+ return resource.arrayOffset() + getReadOffset();
+ } else {
+ return 0;
+ }
}
@Override
public int getReadableArrayLength() {
- return getReadableBytes();
+ if (hasReadbleArray()) {
+ return getReadableBytes();
+ } else {
+ return 0;
+ }
}
@Override
public ByteBuffer getReadableBuffer() {
+ ProtonBufferUtils.checkIsClosed(this);
return resource.nioBuffer(readOffset,
getReadableBytes()).asReadOnlyBuffer();
}
@@ -837,26 +850,42 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
@Override
public boolean hasWritableArray() {
- return resource.hasArray() && !isReadOnly();
+ return resource.hasArray() && !isReadOnly() && isWritable();
}
@Override
public byte[] getWritableArray() {
- return resource.array();
+ ProtonBufferUtils.checkIsClosed(this);
+
+ if (hasWritableArray()) {
+ return resource.array();
+ } else {
+ throw new UnsupportedOperationException("The buffer does not have
a writable array");
+ }
}
@Override
public int getWritableArrayOffset() {
- return resource.arrayOffset() + getWriteOffset();
+ if (hasWritableArray()) {
+ return resource.arrayOffset() + getWriteOffset();
+ } else {
+ return 0;
+ }
}
@Override
public int getWritableArrayLength() {
- return getWritableBytes();
+ if (hasWritableArray()) {
+ return getWritableBytes();
+ } else {
+ return 0;
+ }
}
@Override
public ByteBuffer getWritableBuffer() {
+ ProtonBufferUtils.checkIsClosed(this);
+
if (hasWritableArray()) {
return ByteBuffer.wrap(resource.array(), resource.arrayOffset() +
writeOffset, getWritableBytes());
} else {
@@ -1000,6 +1029,7 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
@Override
public int indexOf(byte needle, int offset, int length) {
ProtonBufferUtils.checkIsClosed(this);
+ checkIndexOfBounds(offset, length);
final int count = resource.bytesBefore(offset, length, needle);
@@ -1028,7 +1058,7 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
@Override
protected ProtonBuffer transferTheResource() {
try {
- return new Netty4ToProtonBufferAdapter(allocator,
resource.setIndex(readOffset, writeOffset), readOnly);
+ return new Netty4ToProtonBufferAdapter(allocator,
resource.setIndex(readOffset, writeOffset), readOnly, implicitGrowthLimit);
} finally {
resource = Unpooled.EMPTY_BUFFER;
}
@@ -1083,6 +1113,14 @@ public final class Netty4ToProtonBufferAdapter extends
SharedResource<ProtonBuff
}
}
+ private void checkIndexOfBounds(int index, int size) {
+ if (index < readOffset || writeOffset < index + size) {
+ throw new IndexOutOfBoundsException(
+ "Search range [read " + index + " length " + size +
+ "] is out of bounds: [read " + readOffset + " length " +
getReadableBytes() + "].");
+ }
+ }
+
private void expandOrThrowError(int index, int size, boolean mayExpand) {
if (readCapacity == CLOSED_MARKER) {
throw ProtonBufferUtils.genericBufferIsClosed(this);
diff --git
a/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/ProtonAbstractBufferTest.java
b/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/ProtonAbstractBufferTest.java
index f8988c12..2fbb8e63 100644
---
a/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/ProtonAbstractBufferTest.java
+++
b/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/ProtonAbstractBufferTest.java
@@ -34,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
import java.nio.ReadOnlyBufferException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
@@ -97,7 +98,7 @@ public abstract class ProtonAbstractBufferTest {
}
@BeforeEach
- public void setUp() {
+ public void setUp() throws IOException {
seed = System.currentTimeMillis();
random = new Random();
random.setSeed(seed);
@@ -112,6 +113,29 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void testBufferCompareThrowsIfAnyBufferIsClosed() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer closedBuffer = allocator.allocate(16);
+ ProtonBuffer closedOtherBuffer = allocator.allocate(16);
+ ProtonBuffer openBuffer = allocator.allocate(16)) {
+
+ closedBuffer.writeLong(0x0102030405060708L);
+ closedOtherBuffer.writeLong(0xF0F1F2F3F4F5F6F7L);
+ openBuffer.writeLong(0x0102030405060708L);
+
+ closedBuffer.close();
+ closedOtherBuffer.close();
+
+ assertThrows(NullPointerException.class, () ->
closedBuffer.compareTo(null));
+ assertThrows(NullPointerException.class, () ->
openBuffer.compareTo(null));
+
+ assertThrows(ProtonBufferClosedException.class, () ->
closedBuffer.compareTo(openBuffer));
+ assertThrows(ProtonBufferClosedException.class, () ->
openBuffer.compareTo(closedBuffer));
+ assertThrows(ProtonBufferClosedException.class, () ->
closedBuffer.compareTo(closedOtherBuffer));
+ }
+ }
+
@Test
public void testEqualsSelf() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(24)) {
@@ -121,6 +145,57 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void testToStringWithCharsetMustRenderTheReadableBytes() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buf = allocator.allocate(24)) {
+
+ assertEquals("", buf.toString(StandardCharsets.UTF_8),
+ "buffer with no readable bytes did not render as an empty
string");
+
+ // "cafe" with an accented e, which is two bytes in UTF-8 and one
in ISO-8859-1.
+ buf.writeBytes(new byte[] { 'c', 'a', 'f', (byte) 0xC3, (byte)
0xA9 });
+
+ assertEquals("caf\u00E9", buf.toString(StandardCharsets.UTF_8),
+ "readable bytes were not rendered by the given charset");
+ assertEquals("caf\u00C3\u00A9",
buf.toString(StandardCharsets.ISO_8859_1),
+ "render did not depend on the given charset");
+
+ buf.advanceReadOffset(3);
+ assertEquals("\u00E9", buf.toString(StandardCharsets.UTF_8),
+ "render did not start at the read offset");
+ }
+ }
+
+ @Test
+ public void
testToStringWithCharsetMustRenderTheReadableBytesOfAReadOnlyBuffer() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buf = allocator.allocate(24)) {
+
+ buf.writeBytes("hello".getBytes(StandardCharsets.US_ASCII));
+ buf.convertToReadOnly();
+
+ assertEquals("hello", buf.toString(StandardCharsets.US_ASCII),
+ "read only buffer readable bytes were not rendered");
+
+ buf.advanceReadOffset(2);
+ assertEquals("llo", buf.toString(StandardCharsets.US_ASCII),
+ "read only buffer render did not start at the read
offset");
+ }
+ }
+
+ @Test
+ public void testToStringWithCharsetMustThrowOnClosedBuffer() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buf = allocator.allocate(24)) {
+
+ buf.writeBytes("gone".getBytes(StandardCharsets.US_ASCII));
+ buf.close();
+
+ assertThrows(ProtonBufferClosedException.class, () ->
buf.toString(StandardCharsets.US_ASCII));
+ }
+ }
+
@Test
public void testOffsettedGetOfByteMustBoundsCheckOnNegativeOffset() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8)) {
@@ -448,6 +523,54 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void testWriteBytesMustCopySourceBytesWhateverTheSourceByteOrder() {
+ // 23 bytes takes the long and int steps of a copy and leaves a tail
of single bytes, so bytes
+ // arriving in an order other than the fixed big endian order of a
buffer show up in the copy
+ // instead of passing unnoticed in a short source.
+ final byte[] payload = new byte[23];
+ for (int i = 0; i < payload.length; i++) {
+ payload[i] = (byte) (i + 1);
+ }
+
+ final boolean[] arrayBacked = { true, false, false, false };
+ final ByteOrder[] orders = { ByteOrder.BIG_ENDIAN,
ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN,
+ ByteOrder.nativeOrder() };
+
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator()) {
+ for (int i = 0; i < orders.length; i++) {
+ final String shape = (arrayBacked[i] ? "array-backed" :
"direct") + " " + orders[i];
+
+ // Buffer with room for the bytes already.
+ try (ProtonBuffer buf = allocator.allocate(payload.length)) {
+ buf.writeBytes(byteBufferSource(payload, arrayBacked[i],
orders[i]));
+
+ assertEquals(payload.length, buf.getWriteOffset());
+ assertArrayEquals(payload,
ProtonBufferUtils.toByteArray(buf), "copied bytes, source " + shape);
+ }
+
+ // Same again where the write has to grow the buffer to make
room.
+ try (ProtonBuffer buf = allocator.allocate(4)) {
+ buf.writeBytes(byteBufferSource(payload, arrayBacked[i],
orders[i]));
+
+ assertEquals(payload.length, buf.getWriteOffset());
+ assertArrayEquals(payload,
ProtonBufferUtils.toByteArray(buf),
+ "copied bytes into a grown buffer,
source " + shape);
+ }
+ }
+ }
+ }
+
+ private static ByteBuffer byteBufferSource(byte[] payload, boolean
arrayBacked, ByteOrder order) {
+ // The order is given to both kinds of source: an array backed one is
copied as bytes and so
+ // must be unaffected by it, a direct one is read a value at a time
and must not reorder them.
+ ByteBuffer source = (arrayBacked ? ByteBuffer.wrap(payload.clone())
+ :
ByteBuffer.allocateDirect(payload.length)).order(order);
+ source.put(payload);
+ source.flip();
+ return source;
+ }
+
@Test
public void
testWriteBytesHeapByteBufferMustExpandCapacityIfBufferIsTooSmall() {
// With zero offsets
@@ -1815,6 +1938,50 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void
testEnsureWritableWithoutCompactionMustNotGrowWhenSpaceIsAlreadyAvailable() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8)) {
+ buf.writeInt(0x01020304);
+ buf.readShort();
+
+ // Four bytes were read back out of the eight that were written,
so the request below is
+ // for exactly the space the buffer already has.
+ assertEquals(2, buf.getReadableBytes());
+ assertEquals(4, buf.getWritableBytes());
+
+ buf.ensureWritable(4, 8, false);
+
+ assertEquals(8, buf.capacity());
+ assertEquals(2, buf.getReadOffset());
+ assertEquals(4, buf.getWriteOffset());
+ assertEquals(2, buf.getReadableBytes());
+ assertEquals(4, buf.getWritableBytes());
+ assertEquals((short) 0x0304, buf.readShort());
+ }
+ }
+
+ @Test
+ public void
testEnsureWritableWithCompactionMustNotCompactWhenSpaceIsAlreadyAvailable() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8)) {
+ buf.writeInt(0x01020304);
+ buf.readShort();
+
+ assertEquals(2, buf.getReadableBytes());
+ assertEquals(4, buf.getWritableBytes());
+
+ // Compaction is allowed here but there is nothing to reclaim for,
as the two consumed
+ // bytes are not needed to cover the request.
+ buf.ensureWritable(4, 8, true);
+
+ assertEquals(8, buf.capacity());
+ assertEquals(2, buf.getReadOffset());
+ assertEquals(4, buf.getWriteOffset());
+ assertEquals(2, buf.getReadableBytes());
+ assertEquals(4, buf.getWritableBytes());
+ assertEquals((short) 0x0304, buf.readShort());
+ }
+ }
+
@Test
public void testEnsureWritableMustExpandBufferCapacity() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8)) {
@@ -1999,6 +2166,27 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void testImplicitLimitImposedAfterBufferTransfered() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8)) {
+ buf.implicitGrowthLimit(8);
+
+ try (ProtonBuffer transfer = buf.transfer()) {
+ transfer.writeLong(0x0102030405060708L);
+
+ assertThrows(IndexOutOfBoundsException.class, () ->
transfer.writeByte((byte) 1));
+ assertThrows(IndexOutOfBoundsException.class, () ->
transfer.writeShort((short) 1));
+ assertThrows(IndexOutOfBoundsException.class, () ->
transfer.writeInt(1));
+ assertThrows(IndexOutOfBoundsException.class, () ->
transfer.writeLong(1));
+ assertThrows(IndexOutOfBoundsException.class, () ->
transfer.writeFloat(1));
+ assertThrows(IndexOutOfBoundsException.class, () ->
transfer.writeDouble(1));
+ assertThrows(IndexOutOfBoundsException.class, () ->
transfer.writeBytes(new byte[1]));
+
+ assertEquals(8, transfer.capacity());
+ }
+ }
+ }
+
@Test
public void testBufferFromCopyMustHaveResetImplicitCapacityLimit() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8)) {
@@ -2020,6 +2208,45 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void
testBufferFromReadOnlySourceCopyMustHaveResetImplicitCapacityLimit() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8)) {
+ buf.writeLong(0x0102030405060708L);
+ buf.implicitGrowthLimit(buf.capacity());
+ buf.convertToReadOnly();
+
+ assertTrue(buf.isReadOnly());
+ assertEquals(8, buf.implicitGrowthLimit());
+
+ // A read-only copy of a read-only buffer can share the memory of
the source, which
+ // must not carry over the growth limit that the source happened
to retain.
+ try (ProtonBuffer copy = buf.copy(true)) {
+ assertTrue(copy.isReadOnly());
+ assertEquals(8, copy.getReadableBytes());
+ assertEquals(ProtonBufferUtils.MAX_BUFFER_CAPACITY,
copy.implicitGrowthLimit());
+ }
+ try (ProtonBuffer copy = buf.copy(1, 6, true)) {
+ assertTrue(copy.isReadOnly());
+ assertEquals(6, copy.getReadableBytes());
+ assertEquals(ProtonBufferUtils.MAX_BUFFER_CAPACITY,
copy.implicitGrowthLimit());
+ }
+
+ // A writable copy is always a deep copy and is not limited either.
+ try (ProtonBuffer copy = buf.copy()) {
+ assertFalse(copy.isReadOnly());
+ assertEquals(8, copy.getReadableBytes());
+ assertEquals(ProtonBufferUtils.MAX_BUFFER_CAPACITY,
copy.implicitGrowthLimit());
+ copy.writeByte((byte) 2); // No more implicit limit
+ }
+ try (ProtonBuffer copy = buf.copy(1, 6, false)) {
+ assertFalse(copy.isReadOnly());
+ assertEquals(6, copy.getReadableBytes());
+ assertEquals(ProtonBufferUtils.MAX_BUFFER_CAPACITY,
copy.implicitGrowthLimit());
+ copy.writeByte((byte) 3); // No more implicit limit
+ }
+ }
+ }
+
@Test
public void testBufferFromSplitMustHaveResetImplicitCapacityLimit() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(32)) {
@@ -2078,6 +2305,36 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void
testEnsureWritableBeyondImplicitCapacityLimitMustKeepTheLimit() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buf = allocator.allocate(8).implicitGrowthLimit(8)) {
+
+ buf.writeLong(0x0102030405060708L);
+ assertThrows(IndexOutOfBoundsException.class, () ->
buf.writeByte((byte) 1));
+ assertEquals(8, buf.capacity());
+
+ buf.ensureWritable(8);
+
+ // The explicit growth is not bound by the implicit limit, however
the limit itself
+ // must still be in place for any growth that comes later. The
capacity that the
+ // growth produces is not fixed, only that it is enough to hold
the request.
+ assertTrue(buf.capacity() >= 16, "explicit growth only reached
capacity " + buf.capacity());
+ assertEquals(8, buf.implicitGrowthLimit());
+ assertEquals(8, buf.getWriteOffset());
+
+ buf.writeLong(0x0807060504030201L);
+
+ // Use up the room that was created explicitly, then implicit
growth is refused again.
+ while (buf.getWritableBytes() > 0) {
+ buf.writeByte((byte) 2);
+ }
+
+ assertThrows(IndexOutOfBoundsException.class, () ->
buf.writeByte((byte) 1));
+ assertEquals(8, buf.implicitGrowthLimit());
+ }
+ }
+
@Test
public void testWritesMustThrowIfSizeWouldGoBeyondImplicitCapacityLimit() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator()) {
@@ -4104,6 +4361,72 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void testTransferToMustRespectOffsetBuffers() throws IOException {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buffer = allocator.allocate(8)) {
+ for (byte i = 0; i < 10; i++) {
+ buffer.writeByte(i);
+ }
+
+ final int midpoint = buffer.getReadableBytes() / 2;
+
+ try (ProtonBuffer splitFront = buffer.readSplit(midpoint)) {
+ final long channelStartPos = channel.position();
+ final long channelStartSize = channel.size();
+
+ assertEquals(midpoint, splitFront.getReadableBytes());
+ assertEquals(midpoint, buffer.getReadableBytes());
+ assertEquals(midpoint, buffer.transferTo(channel,
buffer.getReadableBytes()));
+ assertEquals(channelStartPos + midpoint, channel.position());
+ assertEquals(channelStartSize + midpoint, channel.size());
+
+ final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
+
+ channel.position(channelStartPos);
+
+ assertEquals(midpoint, channel.read(byteBuffer));
+
+ byteBuffer.flip();
+
+ for (byte i = 5; i < 10; i++) {
+ assertEquals(i, byteBuffer.get());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testTransferToWithLengthLessThanReadableBytes() throws
IOException {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buffer = allocator.allocate(8)) {
+ final int TO_WRITE = 10;
+ final int TO_TRANSFER = 8;
+
+ for (byte i = 0; i < TO_WRITE; i++) {
+ buffer.writeByte(i);
+ }
+
+ final long channelStartPos = channel.position();
+ final long channelStartSize = channel.size();
+
+ assertEquals(TO_WRITE, buffer.getReadableBytes());
+ assertEquals(TO_TRANSFER, buffer.transferTo(channel, TO_TRANSFER));
+ assertEquals(channelStartPos + TO_TRANSFER, channel.position());
+ assertEquals(channelStartSize + TO_TRANSFER, channel.size());
+
+ final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
+
+ channel.position(channelStartPos);
+
+ assertEquals(TO_TRANSFER, channel.read(byteBuffer));
+
+ byteBuffer.flip();
+
+ for (byte i = 0; i < TO_TRANSFER; i++) {
+ assertEquals(i, byteBuffer.get());
+ }
+ }
+ }
+
@Test
public void testTransferToMustThrowIfBufferIsClosed() throws IOException {
try (ProtonBufferAllocator allocator = createTestCaseAllocator()) {
@@ -4932,13 +5255,48 @@ public abstract class ProtonAbstractBufferTest {
writableBuffer.close();
assertThrows(ProtonBufferClosedException.class, () ->
writableBuffer.componentAccessor());
- var readableBuffer = allocator.allocate(8);
+ ProtonBuffer readableBuffer = allocator.allocate(8);
readableBuffer.writeLong(0);
readableBuffer.close();
assertThrows(ProtonBufferClosedException.class, () ->
readableBuffer.componentAccessor());
}
}
+ @Test
+ public void testRetainedComponentViewsOnClosedBufferMustThrow() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocate(16)) {
+
+ buffer.writeLong(0x0102030405060708L);
+
+ final ProtonBufferComponentAccessor accessor =
buffer.componentAccessor();
+ final ProtonBufferComponent component = accessor.first();
+
+ buffer.close();
+
+ // An open accessor holds the buffer open until it is released
too, which is what leaves
+ // the component handle in hand pointing at a buffer that is then
really closed.
+ accessor.close();
+
+ assertThrows(ProtonBufferClosedException.class, () ->
component.getReadableArray());
+ assertThrows(ProtonBufferClosedException.class, () ->
component.getReadableBuffer());
+ assertThrows(ProtonBufferClosedException.class, () ->
component.getWritableArray());
+ assertThrows(ProtonBufferClosedException.class, () ->
component.getWritableBuffer());
+
+ // The two predicates are the documented way to decide whether to
make those calls, so
+ // they must not go on offering an array that the accessors above
now refuse to hand out.
+ assertFalse(component.hasReadbleArray(), "closed component still
reports a readable array");
+ assertFalse(component.hasWritableArray(), "closed component still
reports a writable array");
+
+ // The range accessors sit on the other side of that guard: rather
than throwing for a
+ // closed component they report an empty range, matching what the
predicates just said.
+ assertEquals(0, component.getReadableArrayOffset(), "closed
component reports a readable offset");
+ assertEquals(0, component.getReadableArrayLength(), "closed
component reports a readable length");
+ assertEquals(0, component.getWritableArrayOffset(), "closed
component reports a writable offset");
+ assertEquals(0, component.getWritableArrayLength(), "closed
component reports a writable length");
+ }
+ }
+
@Test
public void testProtonBufferProvidesAccessToAvailableComponents() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buffer = allocator.allocate(8)) {
@@ -4992,6 +5350,41 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void testComponentWithoutReadableBytesMustNotReportAReadableArray()
{
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buffer = allocator.allocate(8)) {
+ buffer.writeLong(0x0102030405060708L);
+
+ try (ProtonBufferComponentAccessor accessor =
buffer.componentAccessor()) {
+ ProtonBufferComponent component = accessor.first();
+
+ // Nothing has been read, so there is a readable portion for
an array to cover.
+ assertEquals(8, component.getReadableBytes());
+ assertTrue(component.hasReadbleArray(), "component with 8
readable bytes");
+ assertDoesNotThrow(() -> component.getReadableArray());
+ }
+
+ buffer.readLong();
+
+ try (ProtonBufferComponentAccessor accessor =
buffer.componentAccessor()) {
+ ProtonBufferComponent component = accessor.first();
+
+ // Every byte is consumed, so there is no readable portion
left for an array to cover,
+ // which is the guard that the readable array calls are meant
to sit behind.
+ assertEquals(0, component.getReadableBytes());
+ assertFalse(component.hasReadbleArray(), "component with 0
readable bytes reports a readable array");
+ assertThrows(UnsupportedOperationException.class, () ->
component.getReadableArray());
+
+ // Nothing readable is left, so the range accessors report an
empty range rather than
+ // the offset that the consumed bytes left behind.
+ assertEquals(0, component.getReadableArrayOffset(),
+ "component with 0 readable bytes reports a readable
array offset");
+ assertEquals(0, component.getReadableArrayLength(),
+ "component with 0 readable bytes reports a readable
array length");
+ }
+ }
+ }
+
@Test
public void testIteratingComponentMustAllowCollectingBuffersInArray() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator()) {
@@ -5022,7 +5415,7 @@ public abstract class ProtonAbstractBufferTest {
ByteBuffer[] buffers = new ByteBuffer[single.componentCount()];
try (ProtonBufferComponentAccessor accessor =
single.componentAccessor()) {
int index = 0;
- for (var component = accessor.first(); component != null;
component = accessor.next()) {
+ for (ProtonBufferComponent component = accessor.first();
component != null; component = accessor.next()) {
buffers[index] = component.getWritableBuffer();
index++;
}
@@ -5066,8 +5459,8 @@ public abstract class ProtonAbstractBufferTest {
Deque<Integer> list = new LinkedList<Integer>(List.of(1, 2, 3));
int index = 0;
try (ProtonBufferComponentAccessor accessor =
composite.componentAccessor()) {
- for (var component = accessor.first(); component != null;
component = accessor.next()) {
- var buffer = component.getReadableBuffer();
+ for (ProtonBufferComponent component = accessor.first();
component != null; component = accessor.next()) {
+ ByteBuffer buffer = component.getReadableBuffer();
int bufferValue = buffer.getInt();
int expectedValue = list.pollFirst().intValue();
assertEquals(expectedValue, bufferValue);
@@ -5090,7 +5483,7 @@ public abstract class ProtonAbstractBufferTest {
ProtonBuffer buf = allocator.composite(new ProtonBuffer[] {a,
b, c})) {
try (ProtonBufferComponentAccessor accessor =
buf.componentAccessor()) {
int index = 0;
- for (var component = accessor.first(); component != null;
component = accessor.next()) {
+ for (ProtonBufferComponent component = accessor.first();
component != null; component = accessor.next()) {
component.getWritableBuffer().putLong(0x0102030405060708L + 0x1010101010101010L
* index);
index++;
}
@@ -5109,7 +5502,7 @@ public abstract class ProtonAbstractBufferTest {
ProtonBuffer buf = allocator.allocate(0)) {
try (ProtonBufferComponentAccessor accessor =
buf.componentAccessor()) {
// First component may or may not be null such as from the
byte array based buffer
- var component = accessor.first();
+ ProtonBufferComponent component = accessor.first();
if (component != null) {
assertEquals(0, component.getReadableBytes());
assertEquals(0, component.getReadableArrayLength());
@@ -5150,7 +5543,7 @@ public abstract class ProtonAbstractBufferTest {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8)) {
int counter = 0;
try (ProtonBufferComponentAccessor accessor =
buf.componentAccessor()) {
- for (var component = accessor.first(); component != null;
component = accessor.next()) {
+ for (ProtonBufferComponent component = accessor.first();
component != null; component = accessor.next()) {
ByteBuffer buffer = component.getWritableBuffer();
while (buffer.hasRemaining()) {
buffer.put((byte) ++counter);
@@ -5191,7 +5584,7 @@ public abstract class ProtonAbstractBufferTest {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
ProtonBuffer buf = allocator.allocate(8).convertToReadOnly()) {
try (ProtonBufferComponentAccessor accessor =
buf.componentAccessor()) {
- for (var c = accessor.first(); c != null; c = accessor.next())
{
+ for (ProtonBufferComponent c = accessor.first(); c != null; c
= accessor.next()) {
assertEquals(0, c.getWritableBytes());
assertEquals(0, c.getWritableArrayLength());
ByteBuffer byteBuffer = c.getWritableBuffer();
@@ -5251,7 +5644,7 @@ public abstract class ProtonAbstractBufferTest {
byte value = byteBuffer.get();
byteBuffer.clear();
assertEquals(value, target.readByte());
- var cmp = component; // Capture for lambda.
+ ProtonBufferComponent cmp = component; // Capture for
lambda.
assertThrows(IndexOutOfBoundsException.class, () ->
cmp.advanceWriteOffset(9));
component.advanceWriteOffset(1);
}
@@ -5459,7 +5852,7 @@ public abstract class ProtonAbstractBufferTest {
}
@Test
- public void testIndeOfByteMustThrowOnClosedBuffer() {
+ public void testIndexOfByteMustThrowOnClosedBuffer() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator()) {
ProtonBuffer buffer = allocator.allocate(8);
buffer.writeLong(0x0102030405060708L);
@@ -5540,6 +5933,42 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void testIndexOfByteWithLengthPastReadableBytesMustThrow() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator()) {
+ ProtonBuffer buffer = allocator.allocate(16);
+ buffer.writeBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16 });
+
+ // Pull the write offset down by four, which leaves the last four
bytes written but not
+ // readable, and still within the capacity of the buffer.
+ buffer.setWriteOffset(12);
+
+ // A window that ends on the write offset is still inside the
readable bytes.
+ assertEquals(6, buffer.indexOf((byte) 7, 2, 10));
+
+ assertThrows(IndexOutOfBoundsException.class, () ->
buffer.indexOf((byte) 7, 2, 11));
+
+ // The needle sits in the bytes that were released by moving the
write offset back, so
+ // the search must be refused rather than find it there.
+ assertThrows(IndexOutOfBoundsException.class, () ->
buffer.indexOf((byte) 13, 12, 4));
+ }
+ }
+
+ @Test
+ public void testIndexOfByteWithOffsetBeforeReadOffsetMustThrow() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator()) {
+ ProtonBuffer buffer = allocator.allocate(16);
+ buffer.writeBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16 });
+
+ buffer.advanceReadOffset(2);
+
+ assertEquals(6, buffer.indexOf((byte) 7, 2, 10));
+
+ assertThrows(IndexOutOfBoundsException.class, () ->
buffer.indexOf((byte) 7, 1, 10));
+ assertThrows(IndexOutOfBoundsException.class, () ->
buffer.indexOf((byte) 1, 0, 12));
+ }
+ }
+
@Test
public void testIndexOfByteOnEmptyBufferReturnsNoResult() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator()) {
@@ -5740,6 +6169,200 @@ public abstract class ProtonAbstractBufferTest {
}
}
+ @Test
+ public void testBufferComponentReadableBufferMustOnlyCoverReadableBytes() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocateHeapBuffer(16)) {
+
+ buffer.writeBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16 });
+
+ // Move the write offset back so the buffer holds bytes that were
written and then
+ // released, which must not be handed out as readable when the
buffer is not full.
+ buffer.setWriteOffset(8);
+ buffer.readByte();
+
+ assertEquals(1, buffer.componentCount());
+ assertEquals(7, buffer.getReadableBytes());
+
+ final ProtonBufferComponent component =
buffer.componentAccessor().first();
+
+ assertEquals(7, component.getReadableBytes());
+ assertEquals(7, component.getReadableArrayLength());
+
+ ByteBuffer readableBuffer = component.getReadableBuffer();
+
+ assertEquals(7, readableBuffer.remaining());
+
+ byte[] readable = new byte[readableBuffer.remaining()];
+ readableBuffer.get(readable);
+ assertArrayEquals(new byte[] { 2, 3, 4, 5, 6, 7, 8 }, readable);
+ }
+ }
+
+ @Test
+ public void testBufferComponentViewsMustOnlyCoverTheirOwnBytes() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocateHeapBuffer(16)) {
+
+ buffer.writeBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 });
+
+ for (int state = 0; state < 4; ++state) {
+ switch (state) {
+ case 1: // Some of the written bytes have been consumed
+ buffer.advanceReadOffset(4);
+ break;
+ case 2: // Everything the buffer can hold has been written
+ buffer.advanceWriteOffset(buffer.getWritableBytes());
+ break;
+ case 3: // The buffer can no longer be written to at all
+ buffer.convertToReadOnly();
+ break;
+ default:
+ break;
+ }
+
+ assertEquals(1, buffer.componentCount());
+
+ try (ProtonBufferComponentAccessor accessor =
buffer.componentAccessor()) {
+ int visited = 0;
+
+ for (ProtonBufferComponent component :
accessor.components()) {
+ // An implementation is not required to hand out an
exact slice of the
+ // memory that backs the component, so the views are
sized using only
+ // remaining(), never the position, limit or capacity
of the ByteBuffer.
+ ByteBuffer readableBuffer =
component.getReadableBuffer();
+ assertEquals(component.getReadableBytes(),
readableBuffer.remaining(),
+ "readable view size in state " + state);
+
+ byte[] readableBytes = new
byte[readableBuffer.remaining()];
+ readableBuffer.get(readableBytes);
+ for (int i = 0; i < readableBytes.length; ++i) {
+ assertEquals(buffer.getByte(buffer.getReadOffset()
+ i), readableBytes[i],
+ "readable view content at " + i + " in state "
+ state);
+ }
+
+ ByteBuffer writableBuffer =
component.getWritableBuffer();
+ assertEquals(component.getWritableBytes(),
writableBuffer.remaining(),
+ "writable view size in state " + state);
+
+ visited++;
+ }
+
+ assertEquals(1, visited);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testReadBooleanValues() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocate(16)) {
+
+ buffer.writeLong(0xff00ff000000ff11L);
+
+ assertTrue(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertTrue(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertTrue(buffer.readBoolean());
+ assertTrue(buffer.readBoolean());
+
+ assertFalse(buffer.isReadable());
+ }
+ }
+
+ @Test
+ public void testSetBooleanValuesAndReadBack() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocate(16)) {
+
+ buffer.writeLong(0L);
+
+ buffer.setBoolean(1, true);
+ buffer.setBoolean(7, true);
+
+ assertFalse(buffer.readBoolean());
+ assertTrue(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertFalse(buffer.readBoolean());
+ assertTrue(buffer.readBoolean());
+
+ assertFalse(buffer.isReadable());
+ }
+ }
+
+ @Test
+ public void testBufferFillWithValueThatIsNegativeAsByteValue() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocate(16)) {
+
+ buffer.fill((byte) 0xFF);
+ buffer.setWriteOffset(buffer.capacity());
+
+ final int readable = buffer.getReadableBytes();
+
+ assertEquals(16, readable);
+
+ for (int i = 0; i < readable; ++i) {
+ assertEquals(-1, buffer.readByte());
+ }
+
+ assertFalse(buffer.isReadable());
+ }
+ }
+
+ @Test
+ public void testFilledBufferReportsNoWritableArrayFromAccessor() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocate()) {
+
+ buffer.advanceWriteOffset(buffer.capacity());
+
+ try (ProtonBufferComponentAccessor accessor =
buffer.componentAccessor()) {
+ for (ProtonBufferComponent component : accessor.components()) {
+ assertEquals(0, component.getWritableBytes());
+ assertFalse(component.hasWritableArray(), "component with
0 writable bytes reports a writable array");
+ assertThrows(UnsupportedOperationException.class, () ->
component.getWritableArray());
+
+ // Nothing writable is left, so the range accessors report
an empty range rather
+ // than the offset that the written bytes left behind.
+ assertEquals(0, component.getWritableArrayOffset(),
+ "component with 0 writable bytes reports a
writable array offset");
+ assertEquals(0, component.getWritableArrayLength(),
+ "component with 0 writable bytes reports a
writable array length");
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testConsumedBufferReportsNoReadableArrayFromAccessor() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocate()) {
+
+ buffer.advanceWriteOffset(buffer.capacity());
+ buffer.advanceReadOffset(buffer.capacity());
+
+ try (ProtonBufferComponentAccessor accessor =
buffer.componentAccessor()) {
+ for (ProtonBufferComponent component : accessor.components()) {
+ assertEquals(0, component.getReadableBytes());
+ assertFalse(component.hasReadbleArray(), "component with 0
readable bytes reports a readable array");
+ assertThrows(UnsupportedOperationException.class, () ->
component.getReadableArray());
+ assertEquals(0, component.getReadableArrayOffset(),
+ "component with 0 readable bytes reports a
readable array offset");
+ assertEquals(0, component.getReadableArrayLength(),
+ "component with 0 readable bytes reports a
readable array length");
+ }
+ }
+ }
+ }
+
protected static void verifyInaccessible(ProtonBuffer buf) {
verifyReadInaccessible(buf);
@@ -5841,10 +6464,9 @@ public abstract class ProtonAbstractBufferTest {
public static void verifyReadingForEachSingleComponent(ProtonBuffer buf) {
try (ProtonBufferComponentAccessor accessor = buf.componentAccessor())
{
for (ProtonBufferComponent component = accessor.first(); component
!= null; component = accessor.next()) {
- ByteBuffer buffer = component.getReadableBuffer();
- assertEquals(0, buffer.position());
- assertEquals(8, buffer.limit());
- assertEquals(8, buffer.capacity());
+ final ByteBuffer buffer = component.getReadableBuffer();
+
+ assertEquals(component.getReadableBytes(), buffer.remaining());
assertEquals(0x0102030405060708L, buffer.getLong());
if (component.hasReadbleArray()) {
diff --git
a/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/impl/ProtonByteArrayBufferTest.java
b/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/impl/ProtonByteArrayBufferTest.java
index 1832f389..e1a09bc7 100644
---
a/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/impl/ProtonByteArrayBufferTest.java
+++
b/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/impl/ProtonByteArrayBufferTest.java
@@ -18,10 +18,12 @@
package org.apache.qpid.protonj2.buffer.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import org.apache.qpid.protonj2.buffer.ProtonAbstractBufferTest;
import org.apache.qpid.protonj2.buffer.ProtonBuffer;
import org.apache.qpid.protonj2.buffer.ProtonBufferAllocator;
+import org.apache.qpid.protonj2.buffer.ProtonBufferClosedException;
import org.apache.qpid.protonj2.buffer.ProtonBufferComponent;
import org.apache.qpid.protonj2.buffer.ProtonBufferComponentAccessor;
import org.junit.jupiter.api.Test;
@@ -36,6 +38,49 @@ public class ProtonByteArrayBufferTest extends
ProtonAbstractBufferTest {
return new ProtonByteArrayBufferAllocator();
}
+ @Test
+ public void testArrayAccessAPIThrowsBufferClosedWhenClosed() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocate(16)) {
+
+ ProtonByteArrayBuffer byteArrayBuffer = (ProtonByteArrayBuffer)
buffer;
+
+ byteArrayBuffer.writeByte((byte) 0);
+ byteArrayBuffer.close();
+
+ assertThrows(ProtonBufferClosedException.class, () ->
byteArrayBuffer.getReadableBuffer());
+ assertThrows(ProtonBufferClosedException.class, () ->
byteArrayBuffer.getWritableBuffer());
+ assertThrows(ProtonBufferClosedException.class, () ->
byteArrayBuffer.getReadableArray());
+ assertThrows(ProtonBufferClosedException.class, () ->
byteArrayBuffer.getWritableArray());
+ }
+ }
+
+ @Test
+ public void
testImplicitGrowthDoublesTheCapacityEachTimeTheBufferRunsOutOfSpace() {
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buffer = allocator.allocateHeapBuffer(8)) {
+
+ // Keep the growth limit well above the capacities this test
visits so that only the growth
+ // step itself is being observed here.
+ ((ProtonByteArrayBuffer) buffer).implicitGrowthLimit(1024);
+
+ // Record every capacity the buffer takes on while 64 bytes are
appended one at a time, which
+ // for a buffer that doubles each step is 8, then 16, then 32,
then 64.
+ StringBuilder capacityLadder = new
StringBuilder(String.valueOf(buffer.capacity()));
+ int lastCapacity = buffer.capacity();
+ for (int i = 0; i < 64; i++) {
+ buffer.writeByte((byte) i);
+ if (buffer.capacity() != lastCapacity) {
+ lastCapacity = buffer.capacity();
+ capacityLadder.append(' ').append(lastCapacity);
+ }
+ }
+
+ assertEquals("8 16 32 64", capacityLadder.toString(),
+ "Implicit growth should double the capacity, taking 64 bytes
of writes from 8 to 64");
+ }
+ }
+
@Test
public void testBufferExposesNativeAddressValues() {
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
diff --git
a/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/impl/ProtonCompositeBufferImplTest.java
b/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/impl/ProtonCompositeBufferImplTest.java
index a5c6284e..97c0cbd6 100644
---
a/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/impl/ProtonCompositeBufferImplTest.java
+++
b/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/impl/ProtonCompositeBufferImplTest.java
@@ -17,6 +17,7 @@
package org.apache.qpid.protonj2.buffer.impl;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -27,8 +28,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
import java.util.Iterator;
import org.apache.qpid.protonj2.buffer.ProtonAbstractBufferTest;
@@ -37,11 +43,13 @@ import
org.apache.qpid.protonj2.buffer.ProtonBufferAllocator;
import org.apache.qpid.protonj2.buffer.ProtonBufferClosedException;
import org.apache.qpid.protonj2.buffer.ProtonBufferComponent;
import org.apache.qpid.protonj2.buffer.ProtonBufferComponentAccessor;
+import org.apache.qpid.protonj2.buffer.ProtonBufferIterator;
import org.apache.qpid.protonj2.buffer.ProtonBufferReadOnlyException;
import org.apache.qpid.protonj2.buffer.ProtonCompositeBuffer;
import org.apache.qpid.protonj2.buffer.netty.Netty4ProtonBufferAllocator;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import io.netty.buffer.PooledByteBufAllocator;
@@ -55,6 +63,16 @@ public class ProtonCompositeBufferImplTest extends
ProtonAbstractBufferTest {
return new ProtonCompositeBufferAlloactor();
}
+ @Test
+ public void testCreateCompositeWithEmptyBufferArray() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[0])) {
+
+ assertEquals(0, composite.getReadableBytes());
+ assertEquals(0, composite.getWritableBytes());
+ }
+ }
+
@Test
public void
testAppendReadableBufferOntoCompositeWithCapacityHigherThanReadableBytesWhenBothAreReadOnly()
{
try (ProtonBufferAllocator allocator = createTestCaseAllocator();
@@ -898,6 +916,49 @@ public class ProtonCompositeBufferImplTest extends
ProtonAbstractBufferTest {
}
}
+ @Test
+ public void
testComposeWithNestedCompositeInMiddleMustFlattenAllComponents() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonBuffer a = allocator.copy(new byte[] { 1, 2 });
+ ProtonBuffer b = allocator.copy(new byte[] { 3, 4 });
+ ProtonBuffer c = allocator.copy(new byte[] { 5, 6 });
+ ProtonBuffer d = allocator.copy(new byte[] { 7, 8 })) {
+
+ ProtonBuffer nested = allocator.composite(new ProtonBuffer[] { b,
c });
+
+ try (ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] { a, nested, d })) {
+ assertEquals(8, composite.capacity());
+ assertEquals(8, composite.getReadableBytes());
+ assertEquals(4, composite.componentCount());
+
+ byte[] read = new byte[8];
+ composite.readBytes(read, 0, read.length);
+ assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, read);
+ }
+ }
+ }
+
+ @Test
+ public void
testComposeWithNestedCompositeAtFrontMustFlattenAllComponents() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonBuffer b = allocator.copy(new byte[] { 3, 4 });
+ ProtonBuffer c = allocator.copy(new byte[] { 5, 6 });
+ ProtonBuffer d = allocator.copy(new byte[] { 7, 8 })) {
+
+ ProtonBuffer nested = allocator.composite(new ProtonBuffer[] { b,
c });
+
+ try (ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] { nested, d })) {
+ assertEquals(6, composite.capacity());
+ assertEquals(6, composite.getReadableBytes());
+ assertEquals(3, composite.componentCount());
+
+ byte[] read = new byte[6];
+ composite.readBytes(read, 0, read.length);
+ assertArrayEquals(new byte[] { 3, 4, 5, 6, 7, 8 }, read);
+ }
+ }
+ }
+
@Test
public void
testComposingReadOnlyBuffersMustCreateReadOnlyCompositeBuffer() {
try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
@@ -1998,4 +2059,856 @@ public class ProtonCompositeBufferImplTest extends
ProtonAbstractBufferTest {
}
}
}
+
+ @Test
+ public void
testTransferToMustNotExceedRequestedLengthAcrossMultipleComponents(@TempDir
Path parentDir) throws IOException {
+ final byte[] payload = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
+ final int transferLength = 6;
+
+ Path path = parentDir.resolve("transferTo");
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ FileChannel channel = FileChannel.open(path,
StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(payload, 0, 4),
+ allocator.copy(payload, 4, 4) })) {
+
+ // Mask the gathering write support of the file channel so that
the composite
+ // transfers one component at a time, which is where the length
limit is applied.
+ WritableByteChannel channelWrapper = new WritableByteChannel() {
+ @Override
+ public int write(ByteBuffer src) throws IOException {
+ return channel.write(src);
+ }
+
+ @Override
+ public boolean isOpen() {
+ return channel.isOpen();
+ }
+
+ @Override
+ public void close() throws IOException {
+ channel.close();
+ }
+ };
+
+ long position = channel.position();
+ long size = channel.size();
+
+ assertEquals(transferLength, composite.transferTo(channelWrapper,
transferLength));
+
+ assertEquals(position + transferLength, channel.position());
+ assertEquals(size + transferLength, channel.size());
+ assertEquals(transferLength, composite.getReadOffset());
+ assertEquals(payload.length - transferLength,
composite.getReadableBytes());
+
+ ByteBuffer nio = ByteBuffer.allocate(transferLength);
+ assertEquals(transferLength, channel.read(nio, position));
+ nio.flip();
+
+ byte[] written = new byte[transferLength];
+ nio.get(written);
+ assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6 }, written);
+ }
+ }
+
+ @Test
+ public void
testTransferFromMustNotExceedRequestedLengthAcrossMultipleComponents(@TempDir
Path parentDir) throws IOException {
+ final byte[] payload = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
+ final int transferLength = 6;
+
+ Path path = parentDir.resolve("transferFrom");
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ FileChannel channel = FileChannel.open(path,
StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
+
+ channel.write(ByteBuffer.wrap(payload));
+ channel.position(0);
+
+ try (ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] { allocator.allocate(4), allocator.allocate(4) })) {
+
+ assertEquals(transferLength, composite.transferFrom(channel,
transferLength));
+
+ assertEquals(transferLength, composite.getWriteOffset());
+ assertEquals(payload.length - transferLength,
composite.getWritableBytes());
+ assertEquals(transferLength, channel.position());
+
+ byte[] read = new byte[transferLength];
+ composite.readBytes(read, 0, transferLength);
+ assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6 }, read);
+ }
+ }
+ }
+
+ @Test
+ public void
testTransferFromWithPositionMustNotExceedRequestedLengthAcrossMultipleComponents(@TempDir
Path parentDir) throws IOException {
+ final byte[] payload = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
+ final int transferLength = 6;
+
+ Path path = parentDir.resolve("transferFromWithPosition");
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ FileChannel channel = FileChannel.open(path,
StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
+
+ channel.write(ByteBuffer.wrap(payload));
+
+ try (ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] { allocator.allocate(4), allocator.allocate(4) })) {
+
+ assertEquals(transferLength, composite.transferFrom(channel,
0, transferLength));
+
+ assertEquals(transferLength, composite.getWriteOffset());
+ assertEquals(payload.length - transferLength,
composite.getWritableBytes());
+
+ byte[] read = new byte[transferLength];
+ composite.readBytes(read, 0, transferLength);
+ assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6 }, read);
+ }
+ }
+ }
+
+ @Test
+ public void testIndexOfByteOnEmptyCompositeBuffer() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite()) {
+
+ assertEquals(-1, composite.indexOf((byte) 0));
+ }
+ }
+
+ @Test
+ public void
testIndexOfByteMustFindNeedleWhenReadOffsetIsInsideFirstComponent() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }),
+ allocator.copy(new byte[] { 9, 10, 11, 12, 13, 14, 15, 16
}) })) {
+
+ composite.readByte();
+
+ assertEquals(2, composite.indexOf((byte) 3));
+ assertEquals(10, composite.indexOf((byte) 11));
+
+ // The first byte was read before the search so it is no longer in
the search range.
+ assertEquals(-1, composite.indexOf((byte) 1));
+ }
+ }
+
+ @Test
+ public void testIndexOfByteWithOffsetAndLengthMustSpanComponents() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }),
+ allocator.copy(new byte[] { 9, 10, 11, 12, 13, 14, 15, 16
}) })) {
+
+ // Search range starts in the first component and finds the needle
in the second.
+ assertEquals(10, composite.indexOf((byte) 11, 4, 12));
+
+ // Needle ahead of the search range start, and beyond its end, are
both not found.
+ assertEquals(-1, composite.indexOf((byte) 3, 4, 12));
+ assertEquals(-1, composite.indexOf((byte) 11, 4, 6));
+ }
+ }
+
+ @Test
+ public void
testIndexOfByteMustFindNeedleInLargerTrailingComponentWhenPartiallyRead() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8, 9, 10, 11, 12, 13 })
})) {
+
+ composite.readBytes(new byte[2], 0, 2);
+
+ assertEquals(11, composite.indexOf((byte) 12));
+ assertEquals(11, composite.indexOf((byte) 12, 2, 11));
+ }
+ }
+
+ @Test
+ public void
testIndexOfByteMustGiveBufferIndexWhenSearchStartsAtComponentBoundary() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6 }),
+ allocator.copy(new byte[] { 7, 8, 9, 10, 11, 12, 13 })
})) {
+
+ // Leave the read offset exactly at the start of the second
component.
+ composite.advanceReadOffset(6);
+
+ assertEquals(6, composite.indexOf((byte) 7));
+ assertEquals(8, composite.indexOf((byte) 9));
+ assertEquals(12, composite.indexOf((byte) 13));
+
+ // The needle was in the first component which is now fully read.
+ assertEquals(-1, composite.indexOf((byte) 3));
+ }
+ }
+
+ @Test
+ public void
testIndexOfByteWithOffsetMustGiveBufferIndexForTrailingComponent() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6 }),
+ allocator.copy(new byte[] { 7, 8, 9, 10, 11, 12, 13 })
})) {
+
+ // Search range starts at the second component boundary, and
inside it.
+ assertEquals(8, composite.indexOf((byte) 9, 6, 7));
+ assertEquals(8, composite.indexOf((byte) 9, 8, 5));
+
+ // Needle lies beyond the end of the search range.
+ assertEquals(-1, composite.indexOf((byte) 13, 6, 5));
+ }
+ }
+
+ @Test
+ public void
testIndexOfByteWithOffsetMustGiveBufferIndexForThirdComponent() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8 }),
+ allocator.copy(new byte[] { 9, 10, 11, 12, 13, 14, 15, 16
}) })) {
+
+ // Leave the read offset one byte into the third component, which
is the
+ // tenth byte of this buffer.
+ composite.readBytes(new byte[9], 0, 9);
+
+ assertEquals(13, composite.indexOf((byte) 14));
+ assertEquals(13, composite.indexOf((byte) 14, 9, 7));
+
+ // The needle was in the second component which is now fully read.
+ assertEquals(-1, composite.indexOf((byte) 7, 9, 7));
+ }
+ }
+
+ @Test
+ public void testReverseBufferIterationMustCrossComponentBoundary() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6 }),
+ allocator.copy(new byte[] { 7, 8, 9, 10, 11, 12, 13 })
})) {
+
+ ProtonBufferIterator iterator = composite.bufferReverseIterator(8,
6);
+ assertEquals(6, iterator.remaining());
+
+ byte[] read = new byte[6];
+ for (int i = 0; i < read.length; i++) {
+ read[i] = iterator.next();
+ }
+
+ assertArrayEquals(new byte[] { 9, 8, 7, 6, 5, 4 }, read);
+ assertFalse(iterator.hasNext());
+ assertEquals(0, iterator.remaining());
+ assertEquals(2, iterator.offset());
+
+ // Iteration of the components must not move the buffer offsets.
+ assertEquals(0, composite.getReadOffset());
+ assertEquals(13, composite.getWriteOffset());
+ }
+ }
+
+ @Test
+ public void
testReverseBufferIterationOfAllReadableBytesMustCrossComponentBoundary() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6 }),
+ allocator.copy(new byte[] { 7, 8, 9, 10, 11, 12, 13 })
})) {
+
+ ProtonBufferIterator iterator = composite.bufferReverseIterator();
+ assertEquals(13, iterator.remaining());
+
+ byte[] read = new byte[13];
+ for (int i = 0; i < read.length; i++) {
+ read[i] = iterator.next();
+ }
+
+ assertArrayEquals(new byte[] { 13, 12, 11, 10, 9, 8, 7, 6, 5, 4,
3, 2, 1 }, read);
+ assertFalse(iterator.hasNext());
+ assertEquals(0, iterator.remaining());
+ }
+ }
+
+ @Test
+ public void
testReverseBufferIterationMustCrossMultipleComponentBoundaries() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8 }),
+ allocator.copy(new byte[] { 9, 10, 11, 12, 13, 14, 15, 16
}) })) {
+
+ ProtonBufferIterator iterator =
composite.bufferReverseIterator(13, 10);
+ assertEquals(10, iterator.remaining());
+
+ byte[] read = new byte[10];
+ for (int i = 0; i < read.length; i++) {
+ read[i] = iterator.next();
+ }
+
+ assertArrayEquals(new byte[] { 14, 13, 12, 11, 10, 9, 8, 7, 6, 5
}, read);
+ assertFalse(iterator.hasNext());
+ assertEquals(0, iterator.remaining());
+ assertEquals(3, iterator.offset());
+ }
+ }
+
+ @Test
+ public void testBufferIterationMustCrossComponentBoundary() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6 }),
+ allocator.copy(new byte[] { 7, 8, 9, 10, 11, 12, 13 })
})) {
+
+ ProtonBufferIterator iterator = composite.bufferIterator(3, 6);
+ assertEquals(6, iterator.remaining());
+
+ byte[] read = new byte[6];
+ for (int i = 0; i < read.length; i++) {
+ read[i] = iterator.next();
+ }
+
+ assertArrayEquals(new byte[] { 4, 5, 6, 7, 8, 9 }, read);
+ assertFalse(iterator.hasNext());
+ assertEquals(0, iterator.remaining());
+ assertEquals(9, iterator.offset());
+
+ // Iteration of the components must not move the buffer offsets.
+ assertEquals(0, composite.getReadOffset());
+ assertEquals(13, composite.getWriteOffset());
+ }
+ }
+
+ @Test
+ public void testBufferIterationMustCrossMultipleComponentBoundaries() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8 }),
+ allocator.copy(new byte[] { 9, 10, 11, 12, 13, 14, 15, 16
}) })) {
+
+ ProtonBufferIterator iterator = composite.bufferIterator(3, 10);
+ assertEquals(10, iterator.remaining());
+
+ byte[] read = new byte[10];
+ for (int i = 0; i < read.length; i++) {
+ read[i] = iterator.next();
+ }
+
+ assertArrayEquals(new byte[] { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 },
read);
+ assertFalse(iterator.hasNext());
+ assertEquals(0, iterator.remaining());
+ assertEquals(13, iterator.offset());
+ }
+ }
+
+ @Test
+ public void
testBufferIterationOfAllReadableBytesMustCrossMultipleComponentBoundaries() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8 }),
+ allocator.copy(new byte[] { 9, 10, 11, 12, 13, 14, 15, 16
}) })) {
+
+ ProtonBufferIterator iterator = composite.bufferIterator();
+ assertEquals(16, iterator.remaining());
+
+ byte[] read = new byte[16];
+ for (int i = 0; i < read.length; i++) {
+ read[i] = iterator.next();
+ }
+
+ assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16 }, read);
+ assertFalse(iterator.hasNext());
+ assertEquals(0, iterator.remaining());
+ }
+ }
+
+ @Test
+ public void
testComponentAccessorAdvanceReadOffsetMustKeepCompositeReadOffset() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4 }),
+ allocator.copy(new byte[] { 5, 6, 7, 8 }) })) {
+
+ // Leave the composite read offset one byte into the first
component.
+ assertEquals((byte) 1, composite.readByte());
+
+ try (ProtonBufferComponentAccessor accessor =
composite.componentAccessor()) {
+ ProtonBufferComponent component = accessor.firstReadable();
+ assertEquals(3, component.getReadableBytes());
+
+ component.advanceReadOffset(2);
+ }
+
+ assertEquals(3, composite.getReadOffset());
+ assertEquals(5, composite.getReadableBytes());
+
+ // The two bytes skipped by way of the component must not be
served again.
+ assertEquals((byte) 4, composite.readByte());
+ }
+ }
+
+ @Test
+ public void
testComponentAccessorAdvanceReadOffsetMustAccumulateAcrossComponents() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8 }) })) {
+
+ composite.readByte();
+
+ try (ProtonBufferComponentAccessor accessor =
composite.componentAccessor()) {
+ // Consume the remainder of the first component, then two
bytes of the second.
+ accessor.firstReadable().advanceReadOffset(4);
+ assertEquals(5, composite.getReadOffset());
+
+ accessor.next().advanceReadOffset(2);
+ }
+
+ assertEquals(7, composite.getReadOffset());
+ assertEquals(1, composite.getReadableBytes());
+
+ assertEquals((byte) 8, composite.readByte());
+ }
+ }
+
+ @Test
+ public void
testComponentAccessorAdvanceWriteOffsetMustKeepCompositeWriteOffset() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4 }),
+ allocator.allocate(4) })) {
+
+ // The first component is already filled with written bytes, only
the second can be written.
+ assertEquals(4, composite.getWriteOffset());
+
+ try (ProtonBufferComponentAccessor accessor =
composite.componentAccessor()) {
+ ProtonBufferComponent component = accessor.firstWritable();
+ assertEquals(4, component.getWritableBytes());
+
+ component.advanceWriteOffset(1);
+ }
+
+ assertEquals(5, composite.getWriteOffset());
+ assertEquals(5, composite.getReadableBytes());
+
+ composite.writeByte((byte) 9);
+
+ // The advance reserves the byte it skipped, and the bytes written
before it must survive.
+ assertEquals((byte) 2, composite.getByte(1));
+ assertEquals((byte) 9, composite.getByte(5));
+ assertEquals(6, composite.getWriteOffset());
+ }
+ }
+
+ @Test
+ public void
testSingleComponentCompositeComponentAccessorMustMatchWrappedBuffer() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonBuffer buffer = allocator.copy(new byte[] { 1, 2, 3, 4, 5,
6, 7, 8 });
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }) }))
{
+
+ buffer.readByte();
+ composite.readByte();
+
+ try (ProtonBufferComponentAccessor accessor =
buffer.componentAccessor()) {
+ accessor.firstReadable().advanceReadOffset(2);
+ }
+ try (ProtonBufferComponentAccessor accessor =
composite.componentAccessor()) {
+ accessor.firstReadable().advanceReadOffset(2);
+ }
+
+ assertEquals(3, buffer.getReadOffset());
+ assertEquals(3, composite.getReadOffset());
+ assertEquals(buffer.getReadableBytes(),
composite.getReadableBytes());
+ assertEquals(buffer.readByte(), composite.readByte());
+ }
+ }
+
+ @Test
+ public void
testCompositeComponentViewsMustOnlyCoverTheirOwnBytesWhenComponentsShareAnArray()
{
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonBuffer source = allocator.allocate(16);
+ ProtonCompositeBuffer composite = allocator.composite()) {
+
+ source.writeInt(0x01020304);
+ source.writeInt(0x05060708);
+ source.writeInt(0x090A0B0C);
+ source.writeInt(0x0D0E0F10);
+
+ // Two four byte components carved out of the one 16 byte store,
so each owns a range that is
+ // narrower than the array behind it, and the bytes that must not
leak into one view sit
+ // directly next to the range that the view does own.
+ final int[] expectedValues = { 0x01020304, 0x05060708 };
+
+ composite.append(source.split(4));
+ composite.append(source.split(4));
+
+ assertEquals(2, composite.componentCount());
+ assertEquals(8, composite.getReadableBytes());
+
+ int componentIndex = 0;
+ try (ProtonBufferComponentAccessor accessor =
composite.componentAccessor()) {
+ for (ProtonBufferComponent component : accessor.components()) {
+ final int expectedValue = expectedValues[componentIndex];
+
+ assertEquals(4, component.getReadableBytes());
+
+ // The array range first, so that a range that is too wide
or starts in the wrong
+ // place is reported as that fault rather than as a fault
of the view built from it.
+ assertTrue(component.hasReadbleArray());
+
+ byte[] readableArray = component.getReadableArray();
+ int readableArrayOffset =
component.getReadableArrayOffset();
+ assertTrue(readableArray.length >
component.getReadableBytes(),
+ "components must share a backing array that is wider
than either component range");
+ assertEquals(4, component.getReadableArrayLength(),
+ "readable array range of component " + componentIndex
+ " is wider than the component");
+ assertEquals(expectedValue, ByteBuffer.wrap(readableArray,
readableArrayOffset, 4).getInt(),
+ "readable array range of component " + componentIndex
+ " exposed another components bytes");
+
+ ByteBuffer readableBuffer = component.getReadableBuffer();
+ assertEquals(component.getReadableBytes(),
readableBuffer.remaining(),
+ "readable view of component " + componentIndex + " is
wider than the component");
+ assertEquals(expectedValue,
readableBuffer.getInt(readableBuffer.position()),
+ "readable view of component " + componentIndex + "
exposed another components bytes");
+
+ componentIndex++;
+ }
+ }
+
+ assertEquals(2, componentIndex);
+ }
+ }
+
+ @Test
+ public void testCompactionReusesConsumedFrontBuffer() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8 }) })) {
+
+ final byte[] frontArray =
composite.componentAccessor().firstReadable().getReadableArray();
+
+ composite.advanceReadOffset(5);
+
+ assertEquals(3, composite.getReadableBytes());
+ assertEquals(0, composite.getWritableBytes());
+ assertEquals(2, composite.componentCount());
+
+ composite.compact();
+
+ assertEquals(3, composite.getReadableBytes());
+ assertEquals(5, composite.getWritableBytes());
+ assertEquals(2, composite.componentCount());
+
+ assertSame(frontArray,
composite.componentAccessor().firstWritable().getWritableArray());
+ }
+ }
+
+ @Test
+ public void testEnsureWritableCompactionReusesConsumedFrontBuffer() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8 }) })) {
+
+ final byte[] frontArray =
composite.componentAccessor().firstReadable().getReadableArray();
+
+ composite.advanceReadOffset(5);
+
+ assertEquals(3, composite.getReadableBytes());
+ assertEquals(0, composite.getWritableBytes());
+ assertEquals(2, composite.componentCount());
+
+ composite.ensureWritable(5, 5, true);
+
+ assertEquals(3, composite.getReadableBytes());
+ assertEquals(2, composite.componentCount());
+ assertEquals(5, composite.getWritableBytes());
+
+ assertSame(frontArray,
composite.componentAccessor().firstWritable().getWritableArray());
+ }
+ }
+
+ @Test
+ public void testMultiBufferCompactionFromEnsurewritableExactMatch() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3 }),
+ allocator.copy(new byte[] { 4, 5, 6 }),
+ allocator.copy(new byte[] { 7, 8, 9 }) })) {
+
+ final byte[] frontArray =
composite.componentAccessor().firstReadable().getReadableArray();
+
+ composite.advanceReadOffset(6);
+
+ assertEquals(3, composite.getReadableBytes());
+ assertEquals(0, composite.getWritableBytes());
+ assertEquals(3, composite.componentCount());
+
+ composite.ensureWritable(6, 6, true);
+
+ assertEquals(3, composite.getReadableBytes());
+ assertEquals(3, composite.componentCount());
+ assertEquals(6, composite.getWritableBytes());
+
+ assertSame(frontArray,
composite.componentAccessor().firstWritable().getWritableArray());
+ }
+ }
+
+ @Test
+ public void
testEnsureWritableCompactionWhenWritableBytesPartlyCoverRequest() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5, 6 }),
+ allocator.copy(new byte[] { 7, 8, 9, 10, 11, 12 }) })) {
+
+ final byte[] frontArray =
composite.componentAccessor().firstReadable().getReadableArray();
+
+ // Consume the front component and pull the write offset back one
byte, leaving six
+ // consumed bytes that can be reclaimed and a single byte that is
still writable.
+ composite.advanceReadOffset(6);
+ composite.setWriteOffset(11);
+
+ assertEquals(5, composite.getReadableBytes());
+ assertEquals(1, composite.getWritableBytes());
+ assertEquals(2, composite.componentCount());
+
+ // The request is only covered once the consumed bytes are added
to the byte that is
+ // already writable, so compaction must run rather than allocating
another buffer.
+ composite.ensureWritable(7, 7, true);
+
+ assertEquals(2, composite.componentCount());
+ assertEquals(12, composite.capacity());
+ assertEquals(5, composite.getReadableBytes());
+ assertEquals(7, composite.getWritableBytes());
+
+ byte[] tailArray = null;
+ try (ProtonBufferComponentAccessor accessor =
composite.componentAccessor()) {
+ for (ProtonBufferComponent component : accessor.components()) {
+ tailArray = component.getWritableArray();
+ }
+ }
+
+ // The consumed front buffer must be the one that was reused, now
at the tail.
+ assertSame(frontArray, tailArray);
+
+ byte[] readable = new byte[composite.getReadableBytes()];
+ composite.readBytes(readable, 0, readable.length);
+ assertArrayEquals(new byte[] { 7, 8, 9, 10, 11 }, readable);
+
+ // The reclaimed space must be usable without the buffer growing
any further.
+ composite.writeBytes(new byte[] { 20, 21, 22, 23, 24, 25, 26 });
+
+ assertEquals(12, composite.capacity());
+ assertEquals(12, composite.getWriteOffset());
+ assertEquals((byte) 26, composite.getByte(11));
+ }
+ }
+
+ @Test
+ public void
testEnsureWritableCompactionOfFrontBufferKeepsRemainingBytesInOrder() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8 }),
+ allocator.copy(new byte[] { 9, 10, 11, 12, 13, 14, 15, 16
}) })) {
+
+ composite.advanceReadOffset(5);
+
+ assertEquals(11, composite.getReadableBytes());
+ assertEquals(0, composite.getWritableBytes());
+ assertEquals(3, composite.componentCount());
+ assertEquals(16, composite.capacity());
+
+ composite.ensureWritable(5, 5, true);
+
+ // Only the consumed front buffer is reclaimed and it must move to
the end of the chain,
+ // leaving the bytes that are still readable in their original
order and the buffer at
+ // the same size.
+ assertEquals(0, composite.getReadOffset());
+ assertEquals(11, composite.getWriteOffset());
+ assertEquals(11, composite.getReadableBytes());
+ assertEquals(5, composite.getWritableBytes());
+ assertEquals(3, composite.componentCount());
+ assertEquals(16, composite.capacity());
+
+ byte[] readable = new byte[composite.getReadableBytes()];
+ composite.readBytes(readable, 0, readable.length);
+ assertArrayEquals(new byte[] { 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16 }, readable);
+
+ // The reclaimed space must take the next writes without the
buffer growing, and the
+ // whole chain must still read back as one continuous sequence of
bytes.
+ composite.writeBytes(new byte[] { 17, 18, 19, 20, 21 });
+
+ assertEquals(16, composite.capacity());
+ assertEquals(16, composite.getWriteOffset());
+ assertEquals(0, composite.getWritableBytes());
+
+ for (int i = 0; i < composite.getWriteOffset(); i++) {
+ assertEquals((byte) (i + 6), composite.getByte(i));
+ }
+ }
+ }
+
+ @Test
+ public void
testEnsureWritableCompactionOfFullyConsumedCompositeReusesAllBuffers() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(new byte[] { 1, 2, 3, 4, 5 }),
+ allocator.copy(new byte[] { 6, 7, 8, 9, 10 }) })) {
+
+ composite.advanceReadOffset(10);
+
+ assertEquals(0, composite.getReadableBytes());
+ assertEquals(0, composite.getWritableBytes());
+ assertEquals(2, composite.componentCount());
+ assertEquals(10, composite.capacity());
+
+ // A fully consumed buffer that is reused for the next frame must
reclaim every buffer it
+ // already holds rather than appending another one to the chain.
+ composite.ensureWritable(8, 8, true);
+
+ assertEquals(0, composite.getReadOffset());
+ assertEquals(0, composite.getWriteOffset());
+ assertEquals(0, composite.getReadableBytes());
+ assertEquals(10, composite.getWritableBytes());
+ assertEquals(2, composite.componentCount());
+ assertEquals(10, composite.capacity());
+
+ composite.writeBytes(new byte[] { 20, 21, 22, 23, 24, 25, 26, 27
});
+
+ assertEquals(10, composite.capacity());
+ assertEquals(8, composite.getWriteOffset());
+ assertEquals(8, composite.getReadableBytes());
+
+ byte[] written = new byte[composite.getReadableBytes()];
+ composite.readBytes(written, 0, written.length);
+ assertArrayEquals(new byte[] { 20, 21, 22, 23, 24, 25, 26, 27 },
written);
+ }
+ }
+
+ @Test
+ public void testSingleByteReadsAtEveryOffsetMustMatchEquivalentBuffer() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator())
{
+ byte[] payload = new byte[13];
+ for (int i = 0; i < payload.length; i++) {
+ payload[i] = (byte) (i + 1);
+ }
+
+ try (ProtonBuffer equivalent = allocator.copy(payload);
+ ProtonBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.copy(payload, 0, 5),
+ allocator.copy(payload, 5, 3),
+ allocator.copy(payload, 8, 5) })) {
+
+ assertEquals(13, composite.capacity());
+
+ for (int readOffset = 0; readOffset <= payload.length;
readOffset++) {
+ for (int writeOffset = readOffset; writeOffset <=
payload.length; writeOffset++) {
+
equivalent.setReadOffset(readOffset).setWriteOffset(writeOffset);
+
composite.setReadOffset(readOffset).setWriteOffset(writeOffset);
+
+ for (int index = 0; index < composite.capacity();
index++) {
+ assertEquals(equivalent.getByte(index),
composite.getByte(index),
+ "getByte at index " + index + " with read
offset " + readOffset +
+ " and write offset " + writeOffset);
+ }
+
+ if (composite.getReadableBytes() > 0) {
+ assertEquals(equivalent.peekByte(),
composite.peekByte(),
+ "peekByte at read offset " + readOffset + "
with write offset " + writeOffset);
+ assertEquals(readOffset,
composite.getReadOffset(), "peekByte must not consume a byte");
+
+ assertEquals(equivalent.readByte(),
composite.readByte(),
+ "readByte at read offset " + readOffset + "
with write offset " + writeOffset);
+ assertEquals(readOffset + 1,
composite.getReadOffset(), "readByte must consume one byte");
+ } else {
+ assertThrows(IndexOutOfBoundsException.class, ()
-> composite.peekByte(),
+ "peekByte where there are no readable bytes at
read offset " + readOffset);
+ assertThrows(IndexOutOfBoundsException.class, ()
-> composite.readByte(),
+ "readByte where there are no readable bytes at
read offset " + readOffset);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testSingleByteWritesAtEveryOffsetMustMatchEquivalentBuffer() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator())
{
+ byte[] payload = new byte[13];
+ for (int i = 0; i < payload.length; i++) {
+ payload[i] = (byte) (i + 1);
+ }
+
+ try (ProtonBuffer equivalent =
allocator.allocate(payload.length).writeBytes(payload);
+ ProtonBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.allocate(5).writeBytes(payload, 0, 5),
+ allocator.allocate(3).writeBytes(payload, 5, 3),
+ allocator.allocate(5).writeBytes(payload, 8, 5) })) {
+
+ assertEquals(13, composite.capacity());
+
+ for (int readOffset = 0; readOffset <= payload.length;
readOffset++) {
+ for (int writeOffset = readOffset; writeOffset <=
payload.length; writeOffset++) {
+
equivalent.setReadOffset(readOffset).setWriteOffset(writeOffset);
+
composite.setReadOffset(readOffset).setWriteOffset(writeOffset);
+
+ // A single byte written at an absolute index must
land in the chunk that holds
+ // that index, including the space that was released
by moving the write offset
+ // back, and must leave both offsets where they were.
+ for (int index = 0; index < composite.capacity();
index++) {
+ final byte value = (byte) (index - payload.length);
+
+ composite.setByte(index, value);
+ equivalent.setByte(index, value);
+
+ assertEquals(value, composite.getByte(index),
+ "setByte at index " + index + " with read
offset " + readOffset +
+ " and write offset " + writeOffset);
+ }
+
+ assertEquals(readOffset, composite.getReadOffset(),
"setByte must not move the read offset");
+ assertEquals(writeOffset, composite.getWriteOffset(),
"setByte must not move the write offset");
+
+ if (composite.getWritableBytes() > 0) {
+ composite.writeByte((byte) 0x7F);
+ equivalent.writeByte((byte) 0x7F);
+
+ assertEquals(writeOffset + 1,
composite.getWriteOffset(),
+ "writeByte at write offset " + writeOffset + "
must consume one writable byte");
+ assertEquals((byte) 0x7F,
composite.getByte(writeOffset),
+ "writeByte at write offset " + writeOffset + "
must store the given byte");
+ }
+ }
+ }
+
+ // None of the single byte writes above may have needed new
space.
+ assertEquals(payload.length, composite.capacity());
+ assertEquals(payload.length, equivalent.capacity());
+ }
+ }
+ }
+
+ @Test
+ public void testWriteByteOnFullyWrittenCompositeMustGrowToHoldTheByte() {
+ try (ProtonBufferAllocator allocator = createProtonDefaultAllocator();
+ ProtonCompositeBuffer composite = allocator.composite(new
ProtonBuffer[] {
+ allocator.allocate(5).writeBytes(new byte[] { 1, 2, 3, 4,
5 }),
+ allocator.allocate(3).writeBytes(new byte[] { 6, 7, 8 }),
+ allocator.allocate(5).writeBytes(new byte[] { 9, 10, 11,
12, 13 }) })) {
+
+ assertEquals(13, composite.capacity());
+ assertEquals(0, composite.getWritableBytes());
+ assertEquals(3, composite.componentCount());
+
+ // The last chunk has no room left, so the byte must be written
into space that the
+ // growth adds to the end of the chain rather than into the
exhausted chunk.
+ composite.writeByte((byte) 0x7F);
+
+ assertTrue(composite.capacity() > 13);
+ assertEquals(14, composite.getWriteOffset());
+ assertEquals(14, composite.getReadableBytes());
+ assertEquals((byte) 0x7F, composite.getByte(13));
+
+ byte[] readable = new byte[composite.getReadableBytes()];
+ composite.readBytes(readable, 0, readable.length);
+ assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 0x7F }, readable);
+ }
+ }
}
diff --git
a/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/netty/Netty4ProtonBufferAdapterTest.java
b/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/netty/Netty4ProtonBufferAdapterTest.java
index ea9f2a21..65672405 100644
---
a/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/netty/Netty4ProtonBufferAdapterTest.java
+++
b/protonj2/src/test/java/org/apache/qpid/protonj2/buffer/netty/Netty4ProtonBufferAdapterTest.java
@@ -18,6 +18,8 @@
package org.apache.qpid.protonj2.buffer.netty;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.qpid.protonj2.buffer.ProtonBuffer;
import org.apache.qpid.protonj2.buffer.ProtonBufferAllocator;
@@ -37,9 +39,38 @@ class Netty4ProtonBufferAdapterTest extends
NettyBufferAdapterTestBase {
return new
Netty4ProtonBufferAllocator(UnpooledByteBufAllocator.DEFAULT);
}
+ /**
+ * The test here overrides the base test because netty allocates its
buffers using
+ * an algorithm that we cannot fully control without significant effort
which is not
+ * generally worth the small behavioral difference. This test capture the
behavior as
+ * it stands now and will fail in the future if we choose to attempt to
address this
+ * difference.
+ */
+ @Test
@Override
public void testEnsureWritableCanGrowBeyondImplicitCapacityLimit() {
- // Netty 4 buffer allocates more than needed in ensureWritable
+ try (ProtonBufferAllocator allocator = createTestCaseAllocator();
+ ProtonBuffer buf = allocator.allocate(8).implicitGrowthLimit(8)) {
+
+ buf.writeLong(0x0102030405060708L);
+ assertThrows(IndexOutOfBoundsException.class, () ->
buf.writeByte((byte) 1));
+
+ buf.ensureWritable(8);
+
+ // The resize rounds up well past the request, and the extra room
is usable, but the
+ // limit itself is retained and imposed again once the extra room
is used up.
+ assertTrue(buf.capacity() > 16, "netty resized the buffer to
capacity " + buf.capacity());
+ assertEquals(8, buf.implicitGrowthLimit());
+
+ buf.writeLong(0x0807060504030201L);
+
+ while (buf.getWritableBytes() > 0) {
+ buf.writeByte((byte) 2);
+ }
+
+ assertThrows(IndexOutOfBoundsException.class, () ->
buf.writeByte((byte) 1));
+ assertEquals(8, buf.implicitGrowthLimit());
+ }
}
@Test
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]