<?php


namespace CubiStore\Web\Utils;

use RuntimeException;

class Bytes
{
    public static function readUint2LE($bytes, $offset = 0)
    {
        return static::unpackFirst('v', $bytes, $offset, 'int2');
    }

    public static function readUint4LE($bytes, $offset = 0)
    {
        return static::unpackFirst('V', $bytes, $offset, 'int4');
    }

    public static function readUint8LE($bytes, $offset = 0)
    {
        return static::unpackFirst('P', $bytes, $offset, 'int8');
    }


    private static function unpackFirst($format, $data, $offset, $what = 'bytes')
    {
        $result = unpack($format, $data, $offset);

        if (!$result) {
            throw new RuntimeException("Failed reading $what from buffer");
        }

        return reset($result);
    }
}
