Use word arithmetic for SegmentReader

Prior to this change, the start index was treated as a byte index
rather than a word index.
This commit is contained in:
Jonah Beckford 2023-08-31 20:11:47 -07:00 committed by Semisol
parent 7869cefeb9
commit c7d5354f23
Signed by: Semisol
GPG key ID: 0949D3C25C7FD14F
2 changed files with 19 additions and 4 deletions

View file

@ -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();
}
}

View file

@ -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));
}
}