Skip to content

Commit a473659

Browse files
committed
fixes #71: fixed truncating left over bits of last byte
1 parent 3090b04 commit a473659

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

src/EnumSet.php

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -328,19 +328,27 @@ public function setBinaryBitsetLe($bitset)
328328
if (!is_string($bitset)) {
329329
throw new InvalidArgumentException('Bitset must be a string');
330330
}
331-
332-
$size = ceil($this->ordinalMax / 8);
331+
332+
$size = strlen($this->bitset);
333333
$sizeIn = strlen($bitset);
334-
334+
335335
if ($sizeIn < $size) {
336336
// add "\0" if the given bitset is not long enough
337337
$bitset .= str_repeat("\0", $size - $sizeIn);
338338
} elseif ($sizeIn > $size) {
339339
$bitset = substr($bitset, 0, $size);
340340
}
341-
342-
$this->bitset = $bitset;
343-
341+
342+
// truncate out-of-range bits of last byte
343+
$lastByteMaxOrd = $this->ordinalMax % 8;
344+
if ($lastByteMaxOrd === 0) {
345+
$this->bitset = $bitset;
346+
} else {
347+
$lastByte = chr($lastByteMaxOrd) & $bitset[$size - 1];
348+
$this->bitset = substr($bitset, 0, -1) . $lastByte;
349+
}
350+
351+
// reset the iterator position
344352
$this->rewind();
345353
}
346354

tests/MabeEnumTest/EnumSetTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,20 @@ public function testSetBinaryBitsetLe()
368368
$this->assertTrue($enumSet->count() == 3);
369369
}
370370

371+
public function testSetBinaryBitsetLeTruncateHighBits()
372+
{
373+
$enumSet = new EnumSet('MabeEnumTest\TestAsset\Enum65');
374+
foreach (Enum65::getEnumerators() as $enumerator) {
375+
$enumSet->attach($enumerator);
376+
}
377+
378+
$bitset = $enumSet->getBinaryBitsetLe();
379+
$newBitset = substr($bitset, 0, -1) . "\xff\xff";
380+
$enumSet->setBinaryBitsetLe($newBitset);
381+
382+
$this->assertSame(bin2hex($bitset), bin2hex($enumSet->getBinaryBitsetLe()));
383+
}
384+
371385
public function testSetBinaryBitsetBe()
372386
{
373387
$enumSet = new EnumSet('MabeEnumTest\TestAsset\Enum65');

0 commit comments

Comments
 (0)