Debian Codegraph @

lib/3rdParty/composer/brick/math/src/Internal/Calculator.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Brick\Math\Internal;
6
7 use Brick\Math\Exception\RoundingNecessaryException;
8 use Brick\Math\RoundingMode;
9
10 /**
11 * Performs basic operations on arbitrary size integers.
12 *
13 * Unless otherwise specified, all parameters must be validated as non-empty strings of digits,
14 * without leading zero, and with an optional leading minus sign if the number is not zero.
15 *
16 * Any other parameter format will lead to undefined behaviour.
17 * All methods must return strings respecting this format, unless specified otherwise.
18 *
19 * @internal
20 *
21 * @psalm-immutable
22 */
23 abstract class Calculator
24 {
25 /**
26 * The maximum exponent value allowed for the pow() method.
27 */
28 public const MAX_POWER = 1_000_000;
29
30 /**
31 * The alphabet for converting from and to base 2 to 36, lowercase.
32 */
33 public const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
34
35 /**
36 * The Calculator instance in use.
37 */
38 private static ?Calculator $instance = null;
39
40 /**
41 * Sets the Calculator instance to use.
42 *
43 * An instance is typically set only in unit tests: the autodetect is usually the best option.
44 *
45 * @param Calculator|null $calculator The calculator instance, or NULL to revert to autodetect.
46 */
47 final public static function set(?Calculator $calculator) : void
48 {
49 self::$instance = $calculator;
50 }
51
52 /**
53 * Returns the Calculator instance to use.
54 *
55 * If none has been explicitly set, the fastest available implementation will be returned.
56 *
57 * @psalm-pure
58 * @psalm-suppress ImpureStaticProperty
59 */
60 final public static function get() : Calculator
61 {
62 if (self::$instance === null) {
63 /** @psalm-suppress ImpureMethodCall */
64 self::$instance = self::detect();
65 }
66
67 return self::$instance;
68 }
69
70 /**
71 * Returns the fastest available Calculator implementation.
72 *
73 * @codeCoverageIgnore
74 */
75 private static function detect() : Calculator
76 {
77 if (\extension_loaded('gmp')) {
78 return new Calculator\GmpCalculator();
79 }
80
81 if (\extension_loaded('bcmath')) {
82 return new Calculator\BcMathCalculator();
83 }
84
85 return new Calculator\NativeCalculator();
86 }
87
88 /**
89 * Extracts the sign & digits of the operands.
90 *
91 * @return array{bool, bool, string, string} Whether $a and $b are negative, followed by their digits.
92 */
93 final protected function init(string $a, string $b) : array
94 {
95 return [
96 $aNeg = ($a[0] === '-'),
97 $bNeg = ($b[0] === '-'),
98
99 $aNeg ? \substr($a, 1) : $a,
100 $bNeg ? \substr($b, 1) : $b,
101 ];
102 }
103
104 /**
105 * Returns the absolute value of a number.
106 */
107 final public function abs(string $n) : string
108 {
109 return ($n[0] === '-') ? \substr($n, 1) : $n;
110 }
111
112 /**
113 * Negates a number.
114 */
115 final public function neg(string $n) : string
116 {
117 if ($n === '0') {
118 return '0';
119 }
120
121 if ($n[0] === '-') {
122 return \substr($n, 1);
123 }
124
125 return '-' . $n;
126 }
127
128 /**
129 * Compares two numbers.
130 *
131 * @psalm-return -1|0|1
132 *
133 * @return int -1 if the first number is less than, 0 if equal to, 1 if greater than the second number.
134 */
135 final public function cmp(string $a, string $b) : int
136 {
137 [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
138
139 if ($aNeg && ! $bNeg) {
140 return -1;
141 }
142
143 if ($bNeg && ! $aNeg) {
144 return 1;
145 }
146
147 $aLen = \strlen($aDig);
148 $bLen = \strlen($bDig);
149
150 if ($aLen < $bLen) {
151 $result = -1;
152 } elseif ($aLen > $bLen) {
153 $result = 1;
154 } else {
155 $result = $aDig <=> $bDig;
156 }
157
158 return $aNeg ? -$result : $result;
159 }
160
161 /**
162 * Adds two numbers.
163 */
164 abstract public function add(string $a, string $b) : string;
165
166 /**
167 * Subtracts two numbers.
168 */
169 abstract public function sub(string $a, string $b) : string;
170
171 /**
172 * Multiplies two numbers.
173 */
174 abstract public function mul(string $a, string $b) : string;
175
176 /**
177 * Returns the quotient of the division of two numbers.
178 *
179 * @param string $a The dividend.
180 * @param string $b The divisor, must not be zero.
181 *
182 * @return string The quotient.
183 */
184 abstract public function divQ(string $a, string $b) : string;
185
186 /**
187 * Returns the remainder of the division of two numbers.
188 *
189 * @param string $a The dividend.
190 * @param string $b The divisor, must not be zero.
191 *
192 * @return string The remainder.
193 */
194 abstract public function divR(string $a, string $b) : string;
195
196 /**
197 * Returns the quotient and remainder of the division of two numbers.
198 *
199 * @param string $a The dividend.
200 * @param string $b The divisor, must not be zero.
201 *
202 * @return array{string, string} An array containing the quotient and remainder.
203 */
204 abstract public function divQR(string $a, string $b) : array;
205
206 /**
207 * Exponentiates a number.
208 *
209 * @param string $a The base number.
210 * @param int $e The exponent, validated as an integer between 0 and MAX_POWER.
211 *
212 * @return string The power.
213 */
214 abstract public function pow(string $a, int $e) : string;
215
216 /**
217 * @param string $b The modulus; must not be zero.
218 */
219 public function mod(string $a, string $b) : string
220 {
221 return $this->divR($this->add($this->divR($a, $b), $b), $b);
222 }
223
224 /**
225 * Returns the modular multiplicative inverse of $x modulo $m.
226 *
227 * If $x has no multiplicative inverse mod m, this method must return null.
228 *
229 * This method can be overridden by the concrete implementation if the underlying library has built-in support.
230 *
231 * @param string $m The modulus; must not be negative or zero.
232 */
233 public function modInverse(string $x, string $m) : ?string
234 {
235 if ($m === '1') {
236 return '0';
237 }
238
239 $modVal = $x;
240
241 if ($x[0] === '-' || ($this->cmp($this->abs($x), $m) >= 0)) {
242 $modVal = $this->mod($x, $m);
243 }
244
245 [$g, $x] = $this->gcdExtended($modVal, $m);
246
247 if ($g !== '1') {
248 return null;
249 }
250
251 return $this->mod($this->add($this->mod($x, $m), $m), $m);
252 }
253
254 /**
255 * Raises a number into power with modulo.
256 *
257 * @param string $base The base number; must be positive or zero.
258 * @param string $exp The exponent; must be positive or zero.
259 * @param string $mod The modulus; must be strictly positive.
260 */
261 abstract public function modPow(string $base, string $exp, string $mod) : string;
262
263 /**
264 * Returns the greatest common divisor of the two numbers.
265 *
266 * This method can be overridden by the concrete implementation if the underlying library
267 * has built-in support for GCD calculations.
268 *
269 * @return string The GCD, always positive, or zero if both arguments are zero.
270 */
271 public function gcd(string $a, string $b) : string
272 {
273 if ($a === '0') {
274 return $this->abs($b);
275 }
276
277 if ($b === '0') {
278 return $this->abs($a);
279 }
280
281 return $this->gcd($b, $this->divR($a, $b));
282 }
283
284 /**
285 * @return array{string, string, string} GCD, X, Y
286 */
287 private function gcdExtended(string $a, string $b) : array
288 {
289 if ($a === '0') {
290 return [$b, '0', '1'];
291 }
292
293 [$gcd, $x1, $y1] = $this->gcdExtended($this->mod($b, $a), $a);
294
295 $x = $this->sub($y1, $this->mul($this->divQ($b, $a), $x1));
296 $y = $x1;
297
298 return [$gcd, $x, $y];
299 }
300
301 /**
302 * Returns the square root of the given number, rounded down.
303 *
304 * The result is the largest x such that x² ≤ n.
305 * The input MUST NOT be negative.
306 */
307 abstract public function sqrt(string $n) : string;
308
309 /**
310 * Converts a number from an arbitrary base.
311 *
312 * This method can be overridden by the concrete implementation if the underlying library
313 * has built-in support for base conversion.
314 *
315 * @param string $number The number, positive or zero, non-empty, case-insensitively validated for the given base.
316 * @param int $base The base of the number, validated from 2 to 36.
317 *
318 * @return string The converted number, following the Calculator conventions.
319 */
320 public function fromBase(string $number, int $base) : string
321 {
322 return $this->fromArbitraryBase(\strtolower($number), self::ALPHABET, $base);
323 }
324
325 /**
326 * Converts a number to an arbitrary base.
327 *
328 * This method can be overridden by the concrete implementation if the underlying library
329 * has built-in support for base conversion.
330 *
331 * @param string $number The number to convert, following the Calculator conventions.
332 * @param int $base The base to convert to, validated from 2 to 36.
333 *
334 * @return string The converted number, lowercase.
335 */
336 public function toBase(string $number, int $base) : string
337 {
338 $negative = ($number[0] === '-');
339
340 if ($negative) {
341 $number = \substr($number, 1);
342 }
343
344 $number = $this->toArbitraryBase($number, self::ALPHABET, $base);
345
346 if ($negative) {
347 return '-' . $number;
348 }
349
350 return $number;
351 }
352
353 /**
354 * Converts a non-negative number in an arbitrary base using a custom alphabet, to base 10.
355 *
356 * @param string $number The number to convert, validated as a non-empty string,
357 * containing only chars in the given alphabet/base.
358 * @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
359 * @param int $base The base of the number, validated from 2 to alphabet length.
360 *
361 * @return string The number in base 10, following the Calculator conventions.
362 */
363 final public function fromArbitraryBase(string $number, string $alphabet, int $base) : string
364 {
365 // remove leading "zeros"
366 $number = \ltrim($number, $alphabet[0]);
367
368 if ($number === '') {
369 return '0';
370 }
371
372 // optimize for "one"
373 if ($number === $alphabet[1]) {
374 return '1';
375 }
376
377 $result = '0';
378 $power = '1';
379
380 $base = (string) $base;
381
382 for ($i = \strlen($number) - 1; $i >= 0; $i--) {
383 $index = \strpos($alphabet, $number[$i]);
384
385 if ($index !== 0) {
386 $result = $this->add($result, ($index === 1)
387 ? $power
388 : $this->mul($power, (string) $index)
389 );
390 }
391
392 if ($i !== 0) {
393 $power = $this->mul($power, $base);
394 }
395 }
396
397 return $result;
398 }
399
400 /**
401 * Converts a non-negative number to an arbitrary base using a custom alphabet.
402 *
403 * @param string $number The number to convert, positive or zero, following the Calculator conventions.
404 * @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
405 * @param int $base The base to convert to, validated from 2 to alphabet length.
406 *
407 * @return string The converted number in the given alphabet.
408 */
409 final public function toArbitraryBase(string $number, string $alphabet, int $base) : string
410 {
411 if ($number === '0') {
412 return $alphabet[0];
413 }
414
415 $base = (string) $base;
416 $result = '';
417
418 while ($number !== '0') {
419 [$number, $remainder] = $this->divQR($number, $base);
420 $remainder = (int) $remainder;
421
422 $result .= $alphabet[$remainder];
423 }
424
425 return \strrev($result);
426 }
427
428 /**
429 * Performs a rounded division.
430 *
431 * Rounding is performed when the remainder of the division is not zero.
432 *
433 * @param string $a The dividend.
434 * @param string $b The divisor, must not be zero.
435 * @param RoundingMode $roundingMode The rounding mode.
436 *
437 * @throws \InvalidArgumentException If the rounding mode is invalid.
438 * @throws RoundingNecessaryException If RoundingMode::UNNECESSARY is provided but rounding is necessary.
439 *
440 * @psalm-suppress ImpureFunctionCall
441 */
442 final public function divRound(string $a, string $b, RoundingMode $roundingMode) : string
443 {
444 [$quotient, $remainder] = $this->divQR($a, $b);
445
446 $hasDiscardedFraction = ($remainder !== '0');
447 $isPositiveOrZero = ($a[0] === '-') === ($b[0] === '-');
448
449 $discardedFractionSign = function() use ($remainder, $b) : int {
450 $r = $this->abs($this->mul($remainder, '2'));
451 $b = $this->abs($b);
452
453 return $this->cmp($r, $b);
454 };
455
456 $increment = false;
457
458 switch ($roundingMode) {
459 case RoundingMode::UNNECESSARY:
460 if ($hasDiscardedFraction) {
461 throw RoundingNecessaryException::roundingNecessary();
462 }
463 break;
464
465 case RoundingMode::UP:
466 $increment = $hasDiscardedFraction;
467 break;
468
469 case RoundingMode::DOWN:
470 break;
471
472 case RoundingMode::CEILING:
473 $increment = $hasDiscardedFraction && $isPositiveOrZero;
474 break;
475
476 case RoundingMode::FLOOR:
477 $increment = $hasDiscardedFraction && ! $isPositiveOrZero;
478 break;
479
480 case RoundingMode::HALF_UP:
481 $increment = $discardedFractionSign() >= 0;
482 break;
483
484 case RoundingMode::HALF_DOWN:
485 $increment = $discardedFractionSign() > 0;
486 break;
487
488 case RoundingMode::HALF_CEILING:
489 $increment = $isPositiveOrZero ? $discardedFractionSign() >= 0 : $discardedFractionSign() > 0;
490 break;
491
492 case RoundingMode::HALF_FLOOR:
493 $increment = $isPositiveOrZero ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0;
494 break;
495
496 case RoundingMode::HALF_EVEN:
497 $lastDigit = (int) $quotient[-1];
498 $lastDigitIsEven = ($lastDigit % 2 === 0);
499 $increment = $lastDigitIsEven ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0;
500 break;
501
502 default:
503 throw new \InvalidArgumentException('Invalid rounding mode.');
504 }
505
506 if ($increment) {
507 return $this->add($quotient, $isPositiveOrZero ? '1' : '-1');
508 }
509
510 return $quotient;
511 }
512
513 /**
514 * Calculates bitwise AND of two numbers.
515 *
516 * This method can be overridden by the concrete implementation if the underlying library
517 * has built-in support for bitwise operations.
518 */
519 public function and(string $a, string $b) : string
520 {
521 return $this->bitwise('and', $a, $b);
522 }
523
524 /**
525 * Calculates bitwise OR of two numbers.
526 *
527 * This method can be overridden by the concrete implementation if the underlying library
528 * has built-in support for bitwise operations.
529 */
530 public function or(string $a, string $b) : string
531 {
532 return $this->bitwise('or', $a, $b);
533 }
534
535 /**
536 * Calculates bitwise XOR of two numbers.
537 *
538 * This method can be overridden by the concrete implementation if the underlying library
539 * has built-in support for bitwise operations.
540 */
541 public function xor(string $a, string $b) : string
542 {
543 return $this->bitwise('xor', $a, $b);
544 }
545
546 /**
547 * Performs a bitwise operation on a decimal number.
548 *
549 * @param 'and'|'or'|'xor' $operator The operator to use.
550 * @param string $a The left operand.
551 * @param string $b The right operand.
552 */
553 private function bitwise(string $operator, string $a, string $b) : string
554 {
555 [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
556
557 $aBin = $this->toBinary($aDig);
558 $bBin = $this->toBinary($bDig);
559
560 $aLen = \strlen($aBin);
561 $bLen = \strlen($bBin);
562
563 if ($aLen > $bLen) {
564 $bBin = \str_repeat("\x00", $aLen - $bLen) . $bBin;
565 } elseif ($bLen > $aLen) {
566 $aBin = \str_repeat("\x00", $bLen - $aLen) . $aBin;
567 }
568
569 if ($aNeg) {
570 $aBin = $this->twosComplement($aBin);
571 }
572 if ($bNeg) {
573 $bBin = $this->twosComplement($bBin);
574 }
575
576 $value = match ($operator) {
577 'and' => $aBin & $bBin,
578 'or' => $aBin | $bBin,
579 'xor' => $aBin ^ $bBin,
580 };
581
582 $negative = match ($operator) {
583 'and' => $aNeg and $bNeg,
584 'or' => $aNeg or $bNeg,
585 'xor' => $aNeg xor $bNeg,
586 };
587
588 if ($negative) {
589 $value = $this->twosComplement($value);
590 }
591
592 $result = $this->toDecimal($value);
593
594 return $negative ? $this->neg($result) : $result;
595 }
596
597 /**
598 * @param string $number A positive, binary number.
599 */
600 private function twosComplement(string $number) : string
601 {
602 $xor = \str_repeat("\xff", \strlen($number));
603
604 $number ^= $xor;
605
606 for ($i = \strlen($number) - 1; $i >= 0; $i--) {
607 $byte = \ord($number[$i]);
608
609 if (++$byte !== 256) {
610 $number[$i] = \chr($byte);
611 break;
612 }
613
614 $number[$i] = "\x00";
615
616 if ($i === 0) {
617 $number = "\x01" . $number;
618 }
619 }
620
621 return $number;
622 }
623
624 /**
625 * Converts a decimal number to a binary string.
626 *
627 * @param string $number The number to convert, positive or zero, only digits.
628 */
629 private function toBinary(string $number) : string
630 {
631 $result = '';
632
633 while ($number !== '0') {
634 [$number, $remainder] = $this->divQR($number, '256');
635 $result .= \chr((int) $remainder);
636 }
637
638 return \strrev($result);
639 }
640
641 /**
642 * Returns the positive decimal representation of a binary number.
643 *
644 * @param string $bytes The bytes representing the number.
645 */
646 private function toDecimal(string $bytes) : string
647 {
648 $result = '0';
649 $power = '1';
650
651 for ($i = \strlen($bytes) - 1; $i >= 0; $i--) {
652 $index = \ord($bytes[$i]);
653
654 if ($index !== 0) {
655 $result = $this->add($result, ($index === 1)
656 ? $power
657 : $this->mul($power, (string) $index)
658 );
659 }
660
661 if ($i !== 0) {
662 $power = $this->mul($power, '256');
663 }
664 }
665
666 return $result;
667 }
668 }