~earboxer/bare-mess-php

0a068dfea48f91c4590a88f58081254c72ca282f — Zach DeCook 4 years ago 4350845
* I8, I16, I32, I64: Implement mess
7 files changed, 64 insertions(+), 0 deletions(-)

A src/I.php
A src/I16.php
A src/I32.php
A src/I64.php
A src/I8.php
A src/Is.php
M tests/PrimitivesTest.php
A src/I.php => src/I.php +25 -0
@@ 0,0 1,25 @@
<?php

namespace BareMess;

abstract class I
{
    use Mutatable;
    private int $value = 0;

    public function mess()
    {
        $mess = '';
        for ($i = 0; $i < get_called_class()::BYTES; $i++) {
            // BARE encodes integers as little-endian (least significant first).
            // Twos complement.
            if ($this->value <= 0) {
                // chr makes binary string of least significant byte.
                $mess .= chr(abs($this->value) >> ($i * 8));
            } else {
                $mess .= chr(0xFF - (($this->value - 1) >> ($i * 8)) );
            }
        }
        return $mess;
    }
}

A src/I16.php => src/I16.php +1 -0
@@ 0,0 1,1 @@
Is.php
\ No newline at end of file

A src/I32.php => src/I32.php +1 -0
@@ 0,0 1,1 @@
Is.php
\ No newline at end of file

A src/I64.php => src/I64.php +1 -0
@@ 0,0 1,1 @@
Is.php
\ No newline at end of file

A src/I8.php => src/I8.php +1 -0
@@ 0,0 1,1 @@
Is.php
\ No newline at end of file

A src/Is.php => src/Is.php +8 -0
@@ 0,0 1,8 @@
<?php

namespace BareMess;

class I8 extends I {public const BYTES = 1;}
class I16 extends I {public const BYTES = 2;}
class I32 extends I {public const BYTES = 4;}
class I64 extends I {public const BYTES = 8;}

M tests/PrimitivesTest.php => tests/PrimitivesTest.php +27 -0
@@ 3,6 3,7 @@
namespace BareMess\Tests;

use BareMess\Example\PublicKey;
use BareMess\{I8,I16,I32,I64};
use BareMess\{U8,U16,U32,U64};
use PHPUnit\Framework\TestCase;



@@ 30,6 31,32 @@ class PrimitivesTest extends TestCase
        $this->assertEquals($value, $pk3->get());
    }

    public function testIs()
    {
        $i8 = new I8();
        $this->assertEquals("\0", $i8->mess());
        $i8->set(1);
        $this->assertEquals("\xFF", $i8->mess());
        $i8->set(-1);
        $this->assertEquals("\x01", $i8->mess());

        $i64 = new I64();
        $this->assertEquals(0, $i64->get());
        // Largest representable value.
        $i64->set(0x7FFFFFFFFFFFFFFF);
        // Twos complement max int looks like 0b1000...0001,
        // note that this is little endian.
        $this->assertEquals("\x01\0\0\0\0\0\0\x80", $i64->mess());

        // Smallest representable value
        $i64->set(-1 << 63);
        $this->assertEquals(-0x7FFFFFFFFFFFFFFF - 1, $i64->get());
        $this->assertEquals("\0\0\0\0\0\0\0\x80", $i64->mess());

        $i64->set(1);
        $this->assertEquals("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", $i64->mess());
    }

    public function testUs()
    {
        $u8 = new U8();