<?php


namespace Mainto\RpcServer\Util\Binary;


use InvalidArgumentException;

class LittleEndian extends Endian{
    public static function uint32ToStr (int $int): string {
        return chr($int & 0xFF).chr($int >> 8 & 0xFF).chr($int >> 16 & 0xFF).chr($int >> 24 & 0xFF);
    }

    public static function strToUint32 (string $str): int {
        if (strlen($str) < 4) {
            throw new InvalidArgumentException("strToUint32: str len is too small");
        }

        return ord($str[3]) << 24 | (ord($str[2]) << 16) | (ord($str[1]) << 8) | (ord($str[0]));
    }

    public static function strToUint64 (string $str): int {
        if (strlen($str) < 8) {
            throw new InvalidArgumentException("strToUint64: str len is too small");
        }

        return ord($str[5]) << 56 | ord($str[5]) << 48 | ord($str[5]) << 40 | ord($str[4]) << 32
            | ord($str[3]) << 24 | (ord($str[2]) << 16) | (ord($str[1]) << 8) | (ord($str[0]));
    }

    public static function strToUint16 (string $str): int {
        if (strlen($str) < 2) {
            throw new InvalidArgumentException("strToUInt16: str len is too small");
        }

        return (ord($str[1]) << 8) | (ord($str[0]));
    }

    public static function putUint16 (&$str, $start, int $int): void {
        $str = substr_replace($str, self::intToUint16($int), $start, 2);
    }

    public static function putUint32 (&$str, $start, int $int): void {
        $str = substr_replace($str, self::intToUint32($int), $start, 4);
    }

    public static function intToUint16 (int $int): string {
        return chr($int & 0xFF).chr($int >> 8 & 0xFF);
    }

    public static function intToUint32 (int $int): string {
        return chr($int & 0xFF).chr($int >> 8 & 0xFF).chr($int >> 16 & 0xFF).chr($int >> 24 & 0xFF);
    }

    public static function intToUint64 (int $int): string {
        return chr($int & 0xFF).chr($int >> 8 & 0xFF).chr($int >> 16 & 0xFF).chr($int >> 24 & 0xFF)
            .chr($int >> 32 & 0xFF).chr($int >> 40 & 0xFF).chr($int >> 48 & 0xFF).chr($int >> 56 & 0xFF);
    }
}