Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

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