Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/ASN1/Util/BigInt.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\ASN1\Util;
6
7 use Brick\Math\BigInteger;
8 use InvalidArgumentException;
9 use Stringable;
10 use Throwable;
11
12 /**
13 * Class to wrap an integer of arbirtary length.
14 * @see \SpomkyLabs\Pki\Test\ASN1\Util\BigIntTest
15 */
16 final class BigInt implements Stringable
17 {
18 /**
19 * Number as a BigInteger object.
20 */
21 private readonly BigInteger $value;
22
23 /**
24 * Number as a base 10 integer string.
25 *
26 * @internal Lazily initialized
27 */
28 private ?string $number = null;
29
30 /**
31 * Number as an integer type.
32 *
33 * @internal Lazily initialized
34 */
35 private ?int $_intNum = null;
36
37 private function __construct(BigInteger|int|string $num)
38 {
39 // convert to BigInteger object
40 if (! $num instanceof BigInteger) {
41 try {
42 $num = BigInteger::of($num);
43 } catch (Throwable) {
44 throw new InvalidArgumentException('Unable to convert to integer.');
45 }
46 }
47 $this->value = $num;
48 }
49
50 public function __toString(): string
51 {
52 return $this->base10();
53 }
54
55 public static function create(BigInteger|int|string $num): self
56 {
57 return new self($num);
58 }
59
60 /**
61 * Initialize from an arbitrary length of octets as an unsigned integer.
62 */
63 public static function fromUnsignedOctets(string $octets): self
64 {
65 if ($octets === '') {
66 throw new InvalidArgumentException('Empty octets.');
67 }
68 return self::create(BigInteger::fromBytes($octets, false));
69 }
70
71 /**
72 * Initialize from an arbitrary length of octets as an signed integer having two's complement encoding.
73 */
74 public static function fromSignedOctets(string $octets): self
75 {
76 if ($octets === '') {
77 throw new InvalidArgumentException('Empty octets.');
78 }
79
80 return self::create(BigInteger::fromBytes($octets));
81 }
82
83 /**
84 * Get the number as a base 10 integer string.
85 */
86 public function base10(): string
87 {
88 if ($this->number === null) {
89 $this->number = $this->value->toBase(10);
90 }
91 return $this->number;
92 }
93
94 /**
95 * Get the number as an integer.
96 */
97 public function toInt(): int
98 {
99 if (! isset($this->_intNum)) {
100 $this->_intNum = $this->value->toInt();
101 }
102 return $this->_intNum;
103 }
104
105 public function getValue(): BigInteger
106 {
107 return $this->value;
108 }
109
110 /**
111 * Get the number as an unsigned integer encoded in binary.
112 */
113 public function unsignedOctets(): string
114 {
115 return $this->value->toBytes(false);
116 }
117
118 /**
119 * Get the number as a signed integer encoded in two's complement binary.
120 */
121 public function signedOctets(): string
122 {
123 return $this->value->toBytes();
124 }
125 }