Skip to content

Commit

Permalink
Fix alignment after reading group of bits
Browse files Browse the repository at this point in the history
  • Loading branch information
wapmorgan committed Feb 7, 2017
1 parent 953483a commit b3bd904
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/BinaryStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@ public function readBits(array $bits) {
}

public function readInteger($sizeInBits = 32) {
if ($this->bitOffset > 0) {
$this->bitOffset = 0;
$this->offset++;
}

if ($sizeInBits >= 16 && $sizeInBits <= 64 && $sizeInBits % 8 == 0) {
$bytes = $sizeInBits / 8;
$data = fread($this->fp, $bytes);
Expand All @@ -160,6 +165,11 @@ public function readInteger($sizeInBits = 32) {
}

public function readFloat($sizeInBits = 32) {
if ($this->bitOffset > 0) {
$this->bitOffset = 0;
$this->offset++;
}

if ($sizeInBits == 32 || $sizeInBits == 64) {
$bytes = $sizeInBits / 8;
$data = fread($this->fp, $bytes);
Expand All @@ -174,6 +184,11 @@ public function readFloat($sizeInBits = 32) {
}

public function readString($sizeInBytes = 1) {
if ($this->bitOffset > 0) {
$this->bitOffset = 0;
$this->offset++;
}

$data = fread($this->fp, $sizeInBytes);
if ($data !== false)
$this->offset += $sizeInBytes;
Expand Down Expand Up @@ -248,7 +263,7 @@ public function readGroup($nameOrFieldsList) {
break;

case 'string':
if ($bitOffset != 0) {
if ($bitOffset > 0) {
$bitOffset = 0;
$offset++;
}
Expand All @@ -261,6 +276,11 @@ public function readGroup($nameOrFieldsList) {
break;

case 'integer':
if ($bitOffset > 0) {
$bitOffset = 0;
$offset++;
}

if ($field_size_in_bits >= 16 && $field_size_in_bits <= 64 && $field_size_in_bits % 8 == 0) {
$bytes = $field_size_in_bits / 8;
$data = null;
Expand All @@ -275,6 +295,11 @@ public function readGroup($nameOrFieldsList) {
break;

case 'float':
if ($bitOffset > 0) {
$bitOffset = 0;
$offset++;
}

if ($field_size_in_bits == 32 || $field_size_in_bits == 64) {
$bytes = $field_size_in_bits / 8;
$data = null;
Expand All @@ -292,6 +317,11 @@ public function readGroup($nameOrFieldsList) {
break;

case 'char':
if ($bitOffset > 0) {
$bitOffset = 0;
$offset++;
}

if ($field_size_in_bits == 1) {
$data = $cache[$offset++];
$group[$field_name] = ord($data);
Expand Down
20 changes: 20 additions & 0 deletions tests/ReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,24 @@ public function testBit() {
'd' => 1,
]));
}

public function testAlignment() {
$s = new BinaryStream($this->createStream(pack('CV', 162, 2147483647)));
$this->assertEquals(array(
'flags' => 162,
'int' => 2147483647
), $s->readGroup(array(
'flags' => 8,
'i:int' => 32,
)));

$s->go(0);
$this->assertEquals(array(
'flags' => 2,
'int' => 2147483647
), $s->readGroup(array(
'flags' => 2,
'i:int' => 32,
)));
}
}

0 comments on commit b3bd904

Please sign in to comment.