~earboxer/bare-mess-php

435084584a997dd2153baebc0ab593d62512ba43 — Zach DeCook 3 years ago 4e900b3
* U8, U16, U32, U64: Rely on pack() to make it messy
2 files changed, 5 insertions(+), 12 deletions(-)

M src/U.php
M tests/PrimitivesTest.php
M src/U.php => src/U.php +0 -12
@@ 7,16 7,4 @@ abstract class U
    use Mutatable;
    use Packable;
    private int $value = 0;

    public function mess()
    {
        // TODO: Don't use strings to encode values.
        // TODO: Use `pack()` instead of coding this ourselves.
        $mess = '';
        for ($i = 0; $i < get_called_class()::BYTES; $i++) {
            // BARE encodes integers as little-endian (least significant first).
            $mess .= chr(($this->value >> ($i * 8))%(1<<8));
        }
        return $mess;
    }
}

M tests/PrimitivesTest.php => tests/PrimitivesTest.php +5 -0
@@ 41,5 41,10 @@ class PrimitivesTest extends TestCase
        $u32 = new U32("\xEF\xBE\xAD\xDE");
        $this->assertEquals(0xDEADBEEF, $u32->get());
        $this->assertEquals("\xEF\xBE\xAD\xDE", $u32->mess());

        // On most computers this decade, this will only work as U63.
        $u64 = new U64("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F");
        $this->assertEquals(0x7FFFFFFFFFFFFFFF, $u64->get());
        $this->assertEquals("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", $u64->mess());
    }
}