Skip to content

Commit 84821ac

Browse files
committed
Merge pull request #9 from klermonte/master
Move the out of boundary check in right place in bit reader
2 parents cdb1b35 + a1a984e commit 84821ac

3 files changed

Lines changed: 40 additions & 5 deletions

File tree

src/BinaryReader.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,8 @@ public function isEof()
114114
}
115115

116116
/**
117-
* @ return bool
117+
* @param int $length
118+
* @return bool
118119
*/
119120
public function canReadBytes($length = 0)
120121
{

src/Type/Bit.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,6 @@ public function read(BinaryReader &$br, $length)
2828
throw new InvalidDataException('The length parameter must be an integer');
2929
}
3030

31-
if (!$br->canReadBytes($length / 8)) {
32-
throw new \OutOfBoundsException('Cannot read bits, it exceeds the boundary of the file');
33-
}
34-
3531
$bitmask = new BitMask();
3632
$result = 0;
3733
$bits = $length;
@@ -54,6 +50,10 @@ public function read(BinaryReader &$br, $length)
5450
}
5551
}
5652

53+
if (!$br->canReadBytes($length / 8)) {
54+
throw new \OutOfBoundsException('Cannot read bits, it exceeds the boundary of the file');
55+
}
56+
5757
if ($bits >= 8) {
5858
$bytes = intval($bits / 8);
5959

test/Type/BitTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ public function testUnsignedBitReader($brBig, $brLittle)
3535
$this->assertEquals(0, $brLittle->readUBits(4));
3636
$this->assertEquals(0, $brBig->readUBits(2));
3737
$this->assertEquals(0, $brLittle->readUBits(2));
38+
39+
$brBig->readUBits(80);
40+
$brLittle->readUBits(80);
41+
42+
$this->assertEquals(0xF, $brBig->readUBits(4));
43+
$this->assertEquals(0xF, $brLittle->readUBits(4));
44+
$this->assertEquals(3, $brBig->readUBits(2));
45+
$this->assertEquals(3, $brLittle->readUBits(2));
3846
}
3947

4048
/**
@@ -100,4 +108,30 @@ public function testExceptionInvalidBitCountLittleEndian($brBig, $brLittle)
100108
{
101109
$brLittle->readBits('foo');
102110
}
111+
112+
/**
113+
* @expectedException \OutOfBoundsException
114+
* @dataProvider binaryReaders
115+
*/
116+
public function testExceptionBitsOnLastBitsBigEndian($brBig, $brLittle)
117+
{
118+
$brBig->setPosition(15);
119+
$brBig->readBits(4);
120+
$brBig->readBits(2);
121+
$brBig->readBits(2);
122+
$brBig->readBits(1);
123+
}
124+
125+
/**
126+
* @expectedException \OutOfBoundsException
127+
* @dataProvider binaryReaders
128+
*/
129+
public function testExceptionBitsOnLastBitsLittleEndian($brBig, $brLittle)
130+
{
131+
$brLittle->setPosition(15);
132+
$brLittle->readBits(4);
133+
$brLittle->readBits(2);
134+
$brLittle->readBits(2);
135+
$brLittle->readBits(1);
136+
}
103137
}

0 commit comments

Comments
 (0)