Debian Codegraph @

lib/3rdParty/composer/web-auth/cose-lib/src/BigInteger.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Cose;
6
7 use Brick\Math\BigInteger as BrickBigInteger;
8 use function chr;
9 use function hex2bin;
10 use function strlen;
11 use function unpack;
12
13 /**
14 * @internal
15 */
16 final class BigInteger
17 {
18 private function __construct(
19 private readonly BrickBigInteger $value
20 ) {
21 }
22
23 public static function createFromBinaryString(string $value): self
24 {
25 $res = unpack('H*', $value);
26 /** @var non-empty-string $data */
27 $data = current($res);
28
29 return new self(BrickBigInteger::fromBase($data, 16));
30 }
31
32 public static function createFromDecimal(int $value): self
33 {
34 return new self(BrickBigInteger::of($value));
35 }
36
37 /**
38 * Converts a BigInteger to a binary string.
39 */
40 public function toBytes(): string
41 {
42 if ($this->value->isEqualTo(BrickBigInteger::zero())) {
43 return '';
44 }
45
46 $temp = $this->value->toBase(16);
47 $temp = 0 !== (strlen($temp) & 1) ? '0' . $temp : $temp;
48 $temp = hex2bin($temp);
49
50 return ltrim($temp, chr(0));
51 }
52
53 /**
54 * Adds two BigIntegers.
55 */
56 public function add(self $y): self
57 {
58 $value = $this->value->plus($y->value);
59
60 return new self($value);
61 }
62
63 /**
64 * Subtracts two BigIntegers.
65 */
66 public function subtract(self $y): self
67 {
68 $value = $this->value->minus($y->value);
69
70 return new self($value);
71 }
72
73 /**
74 * Multiplies two BigIntegers.
75 */
76 public function multiply(self $x): self
77 {
78 $value = $this->value->multipliedBy($x->value);
79
80 return new self($value);
81 }
82
83 /**
84 * Performs modular exponentiation.
85 */
86 public function modPow(self $e, self $n): self
87 {
88 $value = $this->value->modPow($e->value, $n->value);
89
90 return new self($value);
91 }
92
93 /**
94 * Performs modular exponentiation.
95 */
96 public function mod(self $d): self
97 {
98 $value = $this->value->mod($d->value);
99
100 return new self($value);
101 }
102
103 /**
104 * Compares two numbers.
105 */
106 public function compare(self $y): int
107 {
108 return $this->value->compareTo($y->value);
109 }
110 }