diff --git a/agrona/src/main/java/org/agrona/ExpandableRingBuffer.java b/agrona/src/main/java/org/agrona/ExpandableRingBuffer.java index 957593c38..1af2d854a 100644 --- a/agrona/src/main/java/org/agrona/ExpandableRingBuffer.java +++ b/agrona/src/main/java/org/agrona/ExpandableRingBuffer.java @@ -386,15 +386,19 @@ public boolean append(final DirectBuffer srcBuffer, final int srcOffset, final i else if (tailOffset >= headOffset) { final int toEndRemaining = capacity - tailOffset; - if (alignedLength > toEndRemaining && alignedLength <= (totalRemaining - toEndRemaining)) - { - buffer.putInt(tailOffset + MESSAGE_LENGTH_OFFSET, toEndRemaining); - buffer.putInt(tailOffset + MESSAGE_TYPE_OFFSET, MESSAGE_TYPE_PADDING); - tail += toEndRemaining; - } - else + + if (alignedLength > toEndRemaining) { - resize(alignedLength); + if (alignedLength <= (totalRemaining - toEndRemaining)) + { + buffer.putInt(tailOffset + MESSAGE_LENGTH_OFFSET, toEndRemaining); + buffer.putInt(tailOffset + MESSAGE_TYPE_OFFSET, MESSAGE_TYPE_PADDING); + tail += toEndRemaining; + } + else + { + resize(alignedLength); + } } } diff --git a/agrona/src/test/java/org/agrona/ExpandableRingBufferTest.java b/agrona/src/test/java/org/agrona/ExpandableRingBufferTest.java index 4f6c55330..d8fe77057 100644 --- a/agrona/src/test/java/org/agrona/ExpandableRingBufferTest.java +++ b/agrona/src/test/java/org/agrona/ExpandableRingBufferTest.java @@ -181,6 +181,25 @@ public void shouldAppendThenIterateMessagesInOrder() inOrder.verify(mockConsumer).onMessage(any(MutableDirectBuffer.class), anyInt(), eq(MSG_LENGTH_TWO), anyInt()); } + @Test + public void shouldAppendMessagesWithinCapacityWithoutExpanding() + { + final int initialCapacity = 1024; + final int maxCapacity = 2048; + + final ExpandableRingBuffer ringBuffer = new ExpandableRingBuffer(initialCapacity, maxCapacity, false); + + final ExpandableRingBuffer.MessageConsumer mockConsumer = mock(ExpandableRingBuffer.MessageConsumer.class); + when(mockConsumer.onMessage(any(), anyInt(), anyInt(), anyInt())).thenReturn(Boolean.TRUE); + + assertThat(ringBuffer.capacity(), is(initialCapacity)); + + final int messageLength = 32; + ringBuffer.append(TEST_MSG, 0, messageLength); + + assertThat(ringBuffer.capacity(), is(initialCapacity)); + } + @Test public void shouldAppendMessagesWithPaddingWithoutExpanding() {