Fix IndexOutOfBounds when reading a multiple of 8 number of bits

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=163455269
This commit is contained in:
aquilescanta 2017-07-28 04:39:57 -07:00 committed by Oliver Woodman
parent 5bd5af8c60
commit bb04456324
2 changed files with 8 additions and 1 deletions

View File

@ -87,9 +87,13 @@ public final class ParsableBitArrayTest extends TestCase {
result[1] = 0;
testArray.readBits(result, 1, 0);
assertEquals(0, result[1]);
// Test reading a number of bits divisible by 8.
testArray.setPosition(0);
testArray.readBits(result, 0, 16);
assertEquals(TEST_DATA[0], result[0]);
assertEquals(TEST_DATA[1], result[1]);
// Test least significant bits are unmodified.
result[1] = (byte) 0xFF;
testArray.setPosition(16);
testArray.readBits(result, 0, 9);
assertEquals(0x5F, result[0]);
assertEquals(0x7F, result[1]);

View File

@ -192,6 +192,9 @@ public final class ParsableBitArray {
}
// Trailing bits.
int bitsLeft = numBits & 7 /* numBits % 8 */;
if (bitsLeft == 0) {
return;
}
buffer[to] &= 0xFF >> bitsLeft; // Set to 0 the bits that are going to be overwritten.
if (bitOffset + bitsLeft > 8) {
// We read the rest of data[byteOffset] and increase byteOffset.