<?php

if (! function_exists('stringtrim')) {
	function stringtrim(string $string,int $chrs=6): string
	{
		return sprintf('%s...%s',substr($string,0,$chrs),substr($string,-1*$chrs));
	}
}

/**
 * Dump out data into a hex dump
 */
if (! function_exists('hex_dump')) {
	function hex_dump($data,$newline="\n",$width=16): string
	{
		$result = '';

		$pad = '.'; # padding for non-visible characters
		$to = $from = '';

		for ($i=0; $i<=0xFF; $i++) {
			$from .= chr($i);
			$to .= ($i >= 0x20 && $i <= 0x7E) ? chr($i) : $pad;
		}

		$hex = str_split(bin2hex($data),$width*2);
		$chars = str_split(strtr($data,$from,$to),$width);

		$offset = 0;
		foreach ($hex as $i => $line) {
			$result .= sprintf('%08X: %-48s  [%s]%s',
				$offset,
				substr_replace(implode(' ',str_split($line,2)),' ',8*3,0),
				$chars[$i],
				$newline);

			$offset += $width;
		}

		return $result;
	}
}

/**
 * Determine if an int is valid for this environment
 */
if (! function_exists('is_valid_int')) {
	function is_valid_int(mixed $num): bool
	{
		/*
		// check if integers are 64-bit
		static $hasINT64 = NULL;

		if ($hasINT64 === NULL) {
			$hasINT64 = is_int(pow(2, 31)); // 32-bit int are limited to (2^31)-1

			if ((! $hasINT64) && (! defined('PHP_INT_MIN')))
				define('PHP_INT_MIN', ~PHP_INT_MAX);
		}
		*/

		// if integers are 64-bit - no other check required
		return (($num <= PHP_INT_MAX) && ($num >= PHP_INT_MIN));
	}
}

if (! function_exists('fixed_point_int_to_float')) {
	function fixed_point_int_to_float(string $rawdata): float
	{
		if (! strlen($rawdata))
			return 0;

		$len = strlen($rawdata);
		if ($len&($len-1) === 0)
			throw new \Exception('Rawdata len must be a power of 2');

		// Take the first part
		$value = 0;
		for ($i=0; $i<$len/2; $i++)
			$value += ord($rawdata[$len/2+$i])*pow(256,(strlen($rawdata)-1-$i));

		// Take the second part
		$dec = 0;
		for ($i=0; $i<$len/2; $i++)
			$dec += ord($rawdata[$i])*pow(256,(strlen($rawdata)-1-$i));

		return $value+$dec/pow(2,8*$len/2);
	}
}

if (! function_exists('pascal_string')) {
	function pascal_string(string $str): string
	{
		$len = ord(substr($str,0,1));

		return substr($str,1,$len);
	}
}