From c7d5354f2325aa421ea91b71e45e973930fa8f9c Mon Sep 17 00:00:00 2001 From: Jonah Beckford <9566106-jonahbeckford@users.noreply.gitlab.com> Date: Thu, 31 Aug 2023 20:11:47 -0700 Subject: [PATCH] Use word arithmetic for SegmentReader Prior to this change, the start index was treated as a byte index rather than a word index. --- .../src/main/java/org/capnproto/SegmentReader.java | 9 +++++---- .../test/java/org/capnproto/SegmentReaderTest.java | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/runtime/src/main/java/org/capnproto/SegmentReader.java b/runtime/src/main/java/org/capnproto/SegmentReader.java index d24ba34..5d5079a 100644 --- a/runtime/src/main/java/org/capnproto/SegmentReader.java +++ b/runtime/src/main/java/org/capnproto/SegmentReader.java @@ -43,9 +43,10 @@ public class SegmentReader { * Verify that the `size`-long (in words) range starting at word index * `start` is within bounds. */ - public final boolean isInBounds(int start, int size) { - if (start < 0 || size < 0) return false; - long sizeInWords = (long) size * Constants.BYTES_PER_WORD; - return start + sizeInWords <= this.buffer.capacity(); + public final boolean isInBounds(int startInWords, int sizeInWords) { + if (startInWords < 0 || sizeInWords < 0) return false; + long startInBytes = (long) startInWords * Constants.BYTES_PER_WORD; + long sizeInBytes = (long) sizeInWords * Constants.BYTES_PER_WORD; + return startInBytes + sizeInBytes <= this.buffer.capacity(); } } diff --git a/runtime/src/test/java/org/capnproto/SegmentReaderTest.java b/runtime/src/test/java/org/capnproto/SegmentReaderTest.java index 4678963..404d40c 100644 --- a/runtime/src/test/java/org/capnproto/SegmentReaderTest.java +++ b/runtime/src/test/java/org/capnproto/SegmentReaderTest.java @@ -15,4 +15,18 @@ public class SegmentReaderTest { SegmentReader segmentReader = new SegmentReader(byteBuffer, null); MatcherAssert.assertThat(segmentReader.isInBounds(0, Integer.MAX_VALUE), is(false)); } + + @Test + public void oneWordAtLastWordShouldBeInBounds() { + ByteBuffer byteBuffer = ByteBuffer.allocate(64); + SegmentReader segmentReader = new SegmentReader(byteBuffer, null); + MatcherAssert.assertThat(segmentReader.isInBounds(7, 1), is(true)); + } + + @Test + public void twoWordsAtLastWordShouldNotBeInBounds() { + ByteBuffer byteBuffer = ByteBuffer.allocate(64); + SegmentReader segmentReader = new SegmentReader(byteBuffer, null); + MatcherAssert.assertThat(segmentReader.isInBounds(7, 2), is(false)); + } } \ No newline at end of file