Skip to content

Commit

Permalink
Use word arithmetic for SegmentReader
Browse files Browse the repository at this point in the history
Prior to this change, the start index was treated as a byte index
rather than a word index.
  • Loading branch information
Jonah Beckford authored and dwrensha committed Sep 1, 2023
1 parent 2324142 commit 44a975b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
9 changes: 5 additions & 4 deletions runtime/src/main/java/org/capnproto/SegmentReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@ public final long get(int index) {
* 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();
}
}
14 changes: 14 additions & 0 deletions runtime/src/test/java/org/capnproto/SegmentReaderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,18 @@ public void in_boundsCalculationShouldNotOverflow() {
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));
}
}

0 comments on commit 44a975b

Please sign in to comment.