1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace DaveRandom\LibLifxLan; |
4
|
|
|
|
5
|
|
|
const UINT32_MIN = 0; |
6
|
|
|
const UINT32_MAX = 0xffffffff; |
7
|
|
|
|
8
|
|
|
// @codeCoverageIgnoreStart |
9
|
|
|
foreach (['g', 'f', 'e'] as $format) { |
10
|
|
|
if (\pack($format, -0.0) === "\x00\x00\x00\x80") { |
11
|
|
|
\define(__NAMESPACE__ . '\\FLOAT32_CODE', $format); |
12
|
|
|
break; |
13
|
|
|
} |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
if (!\defined(__NAMESPACE__ . '\\FLOAT32_CODE')) { |
17
|
|
|
/** @noinspection PhpUnhandledExceptionInspection */ |
18
|
|
|
throw new \Error('Cannot pack()/unpack() floating point numbers to a 32-bit little-endian representation'); |
19
|
|
|
} |
20
|
|
|
// @codeCoverageIgnoreEnd |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param \DateTimeInterface $dateTime |
24
|
|
|
* @return \DateTimeImmutable |
25
|
|
|
*/ |
26
|
|
|
function datetimeinterface_to_datetimeimmutable(\DateTimeInterface $dateTime): \DateTimeImmutable |
27
|
|
|
{ |
28
|
44 |
|
if ($dateTime instanceof \DateTimeImmutable) { |
29
|
19 |
|
return $dateTime; |
30
|
|
|
} |
31
|
|
|
|
32
|
25 |
|
\assert($dateTime instanceof \DateTime, new \Error('DateTimeInterface is not DateTimeImmutable or DateTime???')); |
33
|
|
|
|
34
|
25 |
|
return \DateTimeImmutable::createFromMutable($dateTime); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param int $timestamp |
39
|
|
|
* @return \DateTimeImmutable |
40
|
|
|
*/ |
41
|
|
|
function nanotime_to_datetimeimmutable(int $timestamp): \DateTimeImmutable |
42
|
|
|
{ |
43
|
1 |
|
static $utcTimeZone; |
44
|
|
|
|
45
|
1 |
|
$usecs = \abs((int)(($timestamp % 1000000000) / 1000)); |
46
|
1 |
|
$secs = (int)($timestamp / 1000000000); |
47
|
|
|
|
48
|
1 |
|
$result = \DateTimeImmutable::createFromFormat( |
49
|
1 |
|
'u U', |
50
|
1 |
|
\sprintf("%06d %d", $usecs, $secs), |
51
|
1 |
|
$utcTimeZone ?? ($utcTimeZone = new \DateTimeZone('UTC')) |
52
|
|
|
); |
53
|
|
|
|
54
|
1 |
|
\assert($result !== false, new \Error("Could not convert nanotime to DateTimeImmutable instance")); |
55
|
|
|
|
56
|
1 |
|
return $result; |
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
function datetimeinterface_to_nanotime(\DateTimeInterface $dateTime): int |
60
|
|
|
{ |
61
|
2 |
|
return (int)$dateTime->format('Uu000'); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
function int16_to_uint16(int $signed): int |
65
|
|
|
{ |
66
|
2 |
|
return $signed < 0 |
67
|
2 |
|
? ($signed & 0x7fff) + ($signed & 0x8000) |
68
|
2 |
|
: $signed & 0x7fff; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
function uint16_to_int16(int $unsigned): int |
72
|
|
|
{ |
73
|
2 |
|
return $unsigned >= 0x8000 |
74
|
2 |
|
? ($unsigned & 0x7fff) - ($unsigned & 0x8000) |
75
|
2 |
|
: $unsigned & 0x7fff; |
76
|
|
|
} |
77
|
|
|
|