Debian Codegraph @

lib/3rdParty/composer/spomky-labs/cbor-php/src/OtherObject/DoublePrecisionFloatObject.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace CBOR\OtherObject;
6
7 use Brick\Math\BigInteger;
8 use CBOR\Normalizable;
9 use CBOR\OtherObject as Base;
10 use CBOR\Utils;
11 use const INF;
12 use InvalidArgumentException;
13 use const NAN;
14 use function strlen;
15
16 final class DoublePrecisionFloatObject extends Base implements Normalizable
17 {
18 public static function supportedAdditionalInformation(): array
19 {
20 return [self::OBJECT_DOUBLE_PRECISION_FLOAT];
21 }
22
23 public static function createFromFloat(float $number): self
24 {
25 $value = match (true) {
26 is_nan($number) => hex2bin('7FF8000000000000'),
27 is_infinite($number) && $number > 0 => hex2bin('7FF0000000000000'),
28 is_infinite($number) && $number < 0 => hex2bin('FFF0000000000000'),
29 default => (fn (): string => unpack('S', "\x01\x00")[1] === 1 ? strrev(pack('d', $number)) : pack(
30 'd',
31 $number
32 ))(),
33 };
34
35 return new self(self::OBJECT_DOUBLE_PRECISION_FLOAT, $value);
36 }
37
38 public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
39 {
40 return new self($additionalInformation, $data);
41 }
42
43 public static function create(string $value): self
44 {
45 if (strlen($value) !== 8) {
46 throw new InvalidArgumentException('The value is not a valid double precision floating point');
47 }
48
49 return new self(self::OBJECT_DOUBLE_PRECISION_FLOAT, $value);
50 }
51
52 public function normalize(): float|int
53 {
54 $exponent = $this->getExponent();
55 $mantissa = $this->getMantissa();
56 $sign = $this->getSign();
57
58 if ($exponent === 0) {
59 $val = $mantissa * 2 ** (-(1022 + 52));
60 } elseif ($exponent !== 0b11111111111) {
61 $val = ($mantissa + (1 << 52)) * 2 ** ($exponent - (1023 + 52));
62 } else {
63 $val = $mantissa === 0 ? INF : NAN;
64 }
65
66 return $sign * $val;
67 }
68
69 public function getExponent(): int
70 {
71 $data = $this->data;
72 Utils::assertString($data, 'Invalid data');
73
74 return Utils::binToBigInteger($data)->shiftedRight(52)->and(Utils::hexToBigInteger('7ff'))->toInt();
75 }
76
77 public function getMantissa(): int
78 {
79 $data = $this->data;
80 Utils::assertString($data, 'Invalid data');
81
82 return Utils::binToBigInteger($data)->and(Utils::hexToBigInteger('fffffffffffff'))->toInt();
83 }
84
85 public function getSign(): int
86 {
87 $data = $this->data;
88 Utils::assertString($data, 'Invalid data');
89 $sign = Utils::binToBigInteger($data)->shiftedRight(63);
90
91 return $sign->isEqualTo(BigInteger::one()) ? -1 : 1;
92 }
93 }