Skip to content

Commit dda1c8c

Browse files
authored
Merge pull request #72 from marc-mabe/hotfix/71
fixes #71: fixed truncating left over bits of last byte
2 parents 5a8feea + a473659 commit dda1c8c

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
@@ -333,19 +333,27 @@ public function setBinaryBitsetLe($bitset)
333333
if (!is_string($bitset)) {
334334
throw new InvalidArgumentException('Bitset must be a string');
335335
}
336-
337-
$size = ceil($this->ordinalMax / 8);
336+
337+
$size = strlen($this->bitset);
338338
$sizeIn = strlen($bitset);
339-
339+
340340
if ($sizeIn < $size) {
341341
// add "\0" if the given bitset is not long enough
342342
$bitset .= str_repeat("\0", $size - $sizeIn);
343343
} elseif ($sizeIn > $size) {
344344
$bitset = substr($bitset, 0, $size);
345345
}
346-
347-
$this->bitset = $bitset;
348-
346+
347+
// truncate out-of-range bits of last byte
348+
$lastByteMaxOrd = $this->ordinalMax % 8;
349+
if ($lastByteMaxOrd === 0) {
350+
$this->bitset = $bitset;
351+
} else {
352+
$lastByte = chr($lastByteMaxOrd) & $bitset[$size - 1];
353+
$this->bitset = substr($bitset, 0, -1) . $lastByte;
354+
}
355+
356+
// reset the iterator position
349357
$this->rewind();
350358
}
351359

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)