Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | 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
    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
     * @return int [-1, 0, 1] If the first number is less than, equal to, or greater than the second number.
132
     */
133
    final public function cmp(string $a, string $b) : int
134
    {
135
        [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
136
 
137
        if ($aNeg && ! $bNeg) {
138
            return -1;
139
        }
140
 
141
        if ($bNeg && ! $aNeg) {
142
            return 1;
143
        }
144
 
145
        $aLen = \strlen($aDig);
146
        $bLen = \strlen($bDig);
147
 
148
        if ($aLen < $bLen) {
149
            $result = -1;
150
        } elseif ($aLen > $bLen) {
151
            $result = 1;
152
        } else {
153
            $result = $aDig <=> $bDig;
154
        }
155
 
156
        return $aNeg ? -$result : $result;
157
    }
158
 
159
    /**
160
     * Adds two numbers.
161
     */
162
    abstract public function add(string $a, string $b) : string;
163
 
164
    /**
165
     * Subtracts two numbers.
166
     */
167
    abstract public function sub(string $a, string $b) : string;
168
 
169
    /**
170
     * Multiplies two numbers.
171
     */
172
    abstract public function mul(string $a, string $b) : string;
173
 
174
    /**
175
     * Returns the quotient of the division of two numbers.
176
     *
177
     * @param string $a The dividend.
178
     * @param string $b The divisor, must not be zero.
179
     *
180
     * @return string The quotient.
181
     */
182
    abstract public function divQ(string $a, string $b) : string;
183
 
184
    /**
185
     * Returns the remainder of the division of two numbers.
186
     *
187
     * @param string $a The dividend.
188
     * @param string $b The divisor, must not be zero.
189
     *
190
     * @return string The remainder.
191
     */
192
    abstract public function divR(string $a, string $b) : string;
193
 
194
    /**
195
     * Returns the quotient and remainder of the division of two numbers.
196
     *
197
     * @param string $a The dividend.
198
     * @param string $b The divisor, must not be zero.
199
     *
200
     * @return array{string, string} An array containing the quotient and remainder.
201
     */
202
    abstract public function divQR(string $a, string $b) : array;
203
 
204
    /**
205
     * Exponentiates a number.
206
     *
207
     * @param string $a The base number.
208
     * @param int    $e The exponent, validated as an integer between 0 and MAX_POWER.
209
     *
210
     * @return string The power.
211
     */
212
    abstract public function pow(string $a, int $e) : string;
213
 
214
    /**
215
     * @param string $b The modulus; must not be zero.
216
     */
217
    public function mod(string $a, string $b) : string
218
    {
219
        return $this->divR($this->add($this->divR($a, $b), $b), $b);
220
    }
221
 
222
    /**
223
     * Returns the modular multiplicative inverse of $x modulo $m.
224
     *
225
     * If $x has no multiplicative inverse mod m, this method must return null.
226
     *
227
     * This method can be overridden by the concrete implementation if the underlying library has built-in support.
228
     *
229
     * @param string $m The modulus; must not be negative or zero.
230
     */
231
    public function modInverse(string $x, string $m) : ?string
232
    {
233
        if ($m === '1') {
234
            return '0';
235
        }
236
 
237
        $modVal = $x;
238
 
239
        if ($x[0] === '-' || ($this->cmp($this->abs($x), $m) >= 0)) {
240
            $modVal = $this->mod($x, $m);
241
        }
242
 
243
        [$g, $x] = $this->gcdExtended($modVal, $m);
244
 
245
        if ($g !== '1') {
246
            return null;
247
        }
248
 
249
        return $this->mod($this->add($this->mod($x, $m), $m), $m);
250
    }
251
 
252
    /**
253
     * Raises a number into power with modulo.
254
     *
255
     * @param string $base The base number; must be positive or zero.
256
     * @param string $exp  The exponent; must be positive or zero.
257
     * @param string $mod  The modulus; must be strictly positive.
258
     */
259
    abstract public function modPow(string $base, string $exp, string $mod) : string;
260
 
261
    /**
262
     * Returns the greatest common divisor of the two numbers.
263
     *
264
     * This method can be overridden by the concrete implementation if the underlying library
265
     * has built-in support for GCD calculations.
266
     *
267
     * @return string The GCD, always positive, or zero if both arguments are zero.
268
     */
269
    public function gcd(string $a, string $b) : string
270
    {
271
        if ($a === '0') {
272
            return $this->abs($b);
273
        }
274
 
275
        if ($b === '0') {
276
            return $this->abs($a);
277
        }
278
 
279
        return $this->gcd($b, $this->divR($a, $b));
280
    }
281
 
282
    /**
283
     * @return array{string, string, string} GCD, X, Y
284
     */
285
    private function gcdExtended(string $a, string $b) : array
286
    {
287
        if ($a === '0') {
288
            return [$b, '0', '1'];
289
        }
290
 
291
        [$gcd, $x1, $y1] = $this->gcdExtended($this->mod($b, $a), $a);
292
 
293
        $x = $this->sub($y1, $this->mul($this->divQ($b, $a), $x1));
294
        $y = $x1;
295
 
296
        return [$gcd, $x, $y];
297
    }
298
 
299
    /**
300
     * Returns the square root of the given number, rounded down.
301
     *
302
     * The result is the largest x such that x² ≤ n.
303
     * The input MUST NOT be negative.
304
     */
305
    abstract public function sqrt(string $n) : string;
306
 
307
    /**
308
     * Converts a number from an arbitrary base.
309
     *
310
     * This method can be overridden by the concrete implementation if the underlying library
311
     * has built-in support for base conversion.
312
     *
313
     * @param string $number The number, positive or zero, non-empty, case-insensitively validated for the given base.
314
     * @param int    $base   The base of the number, validated from 2 to 36.
315
     *
316
     * @return string The converted number, following the Calculator conventions.
317
     */
318
    public function fromBase(string $number, int $base) : string
319
    {
320
        return $this->fromArbitraryBase(\strtolower($number), self::ALPHABET, $base);
321
    }
322
 
323
    /**
324
     * Converts a number to an arbitrary base.
325
     *
326
     * This method can be overridden by the concrete implementation if the underlying library
327
     * has built-in support for base conversion.
328
     *
329
     * @param string $number The number to convert, following the Calculator conventions.
330
     * @param int    $base   The base to convert to, validated from 2 to 36.
331
     *
332
     * @return string The converted number, lowercase.
333
     */
334
    public function toBase(string $number, int $base) : string
335
    {
336
        $negative = ($number[0] === '-');
337
 
338
        if ($negative) {
339
            $number = \substr($number, 1);
340
        }
341
 
342
        $number = $this->toArbitraryBase($number, self::ALPHABET, $base);
343
 
344
        if ($negative) {
345
            return '-' . $number;
346
        }
347
 
348
        return $number;
349
    }
350
 
351
    /**
352
     * Converts a non-negative number in an arbitrary base using a custom alphabet, to base 10.
353
     *
354
     * @param string $number   The number to convert, validated as a non-empty string,
355
     *                         containing only chars in the given alphabet/base.
356
     * @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
357
     * @param int    $base     The base of the number, validated from 2 to alphabet length.
358
     *
359
     * @return string The number in base 10, following the Calculator conventions.
360
     */
361
    final public function fromArbitraryBase(string $number, string $alphabet, int $base) : string
362
    {
363
        // remove leading "zeros"
364
        $number = \ltrim($number, $alphabet[0]);
365
 
366
        if ($number === '') {
367
            return '0';
368
        }
369
 
370
        // optimize for "one"
371
        if ($number === $alphabet[1]) {
372
            return '1';
373
        }
374
 
375
        $result = '0';
376
        $power = '1';
377
 
378
        $base = (string) $base;
379
 
380
        for ($i = \strlen($number) - 1; $i >= 0; $i--) {
381
            $index = \strpos($alphabet, $number[$i]);
382
 
383
            if ($index !== 0) {
384
                $result = $this->add($result, ($index === 1)
385
                    ? $power
386
                    : $this->mul($power, (string) $index)
387
                );
388
            }
389
 
390
            if ($i !== 0) {
391
                $power = $this->mul($power, $base);
392
            }
393
        }
394
 
395
        return $result;
396
    }
397
 
398
    /**
399
     * Converts a non-negative number to an arbitrary base using a custom alphabet.
400
     *
401
     * @param string $number   The number to convert, positive or zero, following the Calculator conventions.
402
     * @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
403
     * @param int    $base     The base to convert to, validated from 2 to alphabet length.
404
     *
405
     * @return string The converted number in the given alphabet.
406
     */
407
    final public function toArbitraryBase(string $number, string $alphabet, int $base) : string
408
    {
409
        if ($number === '0') {
410
            return $alphabet[0];
411
        }
412
 
413
        $base = (string) $base;
414
        $result = '';
415
 
416
        while ($number !== '0') {
417
            [$number, $remainder] = $this->divQR($number, $base);
418
            $remainder = (int) $remainder;
419
 
420
            $result .= $alphabet[$remainder];
421
        }
422
 
423
        return \strrev($result);
424
    }
425
 
426
    /**
427
     * Performs a rounded division.
428
     *
429
     * Rounding is performed when the remainder of the division is not zero.
430
     *
431
     * @param string $a            The dividend.
432
     * @param string $b            The divisor, must not be zero.
433
     * @param int    $roundingMode The rounding mode.
434
     *
435
     * @throws \InvalidArgumentException  If the rounding mode is invalid.
436
     * @throws RoundingNecessaryException If RoundingMode::UNNECESSARY is provided but rounding is necessary.
437
     *
438
     * @psalm-suppress ImpureFunctionCall
439
     */
440
    final public function divRound(string $a, string $b, int $roundingMode) : string
441
    {
442
        [$quotient, $remainder] = $this->divQR($a, $b);
443
 
444
        $hasDiscardedFraction = ($remainder !== '0');
445
        $isPositiveOrZero = ($a[0] === '-') === ($b[0] === '-');
446
 
447
        $discardedFractionSign = function() use ($remainder, $b) : int {
448
            $r = $this->abs($this->mul($remainder, '2'));
449
            $b = $this->abs($b);
450
 
451
            return $this->cmp($r, $b);
452
        };
453
 
454
        $increment = false;
455
 
456
        switch ($roundingMode) {
457
            case RoundingMode::UNNECESSARY:
458
                if ($hasDiscardedFraction) {
459
                    throw RoundingNecessaryException::roundingNecessary();
460
                }
461
                break;
462
 
463
            case RoundingMode::UP:
464
                $increment = $hasDiscardedFraction;
465
                break;
466
 
467
            case RoundingMode::DOWN:
468
                break;
469
 
470
            case RoundingMode::CEILING:
471
                $increment = $hasDiscardedFraction && $isPositiveOrZero;
472
                break;
473
 
474
            case RoundingMode::FLOOR:
475
                $increment = $hasDiscardedFraction && ! $isPositiveOrZero;
476
                break;
477
 
478
            case RoundingMode::HALF_UP:
479
                $increment = $discardedFractionSign() >= 0;
480
                break;
481
 
482
            case RoundingMode::HALF_DOWN:
483
                $increment = $discardedFractionSign() > 0;
484
                break;
485
 
486
            case RoundingMode::HALF_CEILING:
487
                $increment = $isPositiveOrZero ? $discardedFractionSign() >= 0 : $discardedFractionSign() > 0;
488
                break;
489
 
490
            case RoundingMode::HALF_FLOOR:
491
                $increment = $isPositiveOrZero ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0;
492
                break;
493
 
494
            case RoundingMode::HALF_EVEN:
495
                $lastDigit = (int) $quotient[-1];
496
                $lastDigitIsEven = ($lastDigit % 2 === 0);
497
                $increment = $lastDigitIsEven ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0;
498
                break;
499
 
500
            default:
501
                throw new \InvalidArgumentException('Invalid rounding mode.');
502
        }
503
 
504
        if ($increment) {
505
            return $this->add($quotient, $isPositiveOrZero ? '1' : '-1');
506
        }
507
 
508
        return $quotient;
509
    }
510
 
511
    /**
512
     * Calculates bitwise AND of two numbers.
513
     *
514
     * This method can be overridden by the concrete implementation if the underlying library
515
     * has built-in support for bitwise operations.
516
     */
517
    public function and(string $a, string $b) : string
518
    {
519
        return $this->bitwise('and', $a, $b);
520
    }
521
 
522
    /**
523
     * Calculates bitwise OR of two numbers.
524
     *
525
     * This method can be overridden by the concrete implementation if the underlying library
526
     * has built-in support for bitwise operations.
527
     */
528
    public function or(string $a, string $b) : string
529
    {
530
        return $this->bitwise('or', $a, $b);
531
    }
532
 
533
    /**
534
     * Calculates bitwise XOR of two numbers.
535
     *
536
     * This method can be overridden by the concrete implementation if the underlying library
537
     * has built-in support for bitwise operations.
538
     */
539
    public function xor(string $a, string $b) : string
540
    {
541
        return $this->bitwise('xor', $a, $b);
542
    }
543
 
544
    /**
545
     * Performs a bitwise operation on a decimal number.
546
     *
547
     * @param 'and'|'or'|'xor' $operator The operator to use.
548
     * @param string           $a        The left operand.
549
     * @param string           $b        The right operand.
550
     */
551
    private function bitwise(string $operator, string $a, string $b) : string
552
    {
553
        [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
554
 
555
        $aBin = $this->toBinary($aDig);
556
        $bBin = $this->toBinary($bDig);
557
 
558
        $aLen = \strlen($aBin);
559
        $bLen = \strlen($bBin);
560
 
561
        if ($aLen > $bLen) {
562
            $bBin = \str_repeat("\x00", $aLen - $bLen) . $bBin;
563
        } elseif ($bLen > $aLen) {
564
            $aBin = \str_repeat("\x00", $bLen - $aLen) . $aBin;
565
        }
566
 
567
        if ($aNeg) {
568
            $aBin = $this->twosComplement($aBin);
569
        }
570
        if ($bNeg) {
571
            $bBin = $this->twosComplement($bBin);
572
        }
573
 
574
        switch ($operator) {
575
            case 'and':
576
                $value = $aBin & $bBin;
577
                $negative = ($aNeg and $bNeg);
578
                break;
579
 
580
            case 'or':
581
                $value = $aBin | $bBin;
582
                $negative = ($aNeg or $bNeg);
583
                break;
584
 
585
            case 'xor':
586
                $value = $aBin ^ $bBin;
587
                $negative = ($aNeg xor $bNeg);
588
                break;
589
 
590
            // @codeCoverageIgnoreStart
591
            default:
592
                throw new \InvalidArgumentException('Invalid bitwise operator.');
593
            // @codeCoverageIgnoreEnd
594
        }
595
 
596
        if ($negative) {
597
            $value = $this->twosComplement($value);
598
        }
599
 
600
        $result = $this->toDecimal($value);
601
 
602
        return $negative ? $this->neg($result) : $result;
603
    }
604
 
605
    /**
606
     * @param string $number A positive, binary number.
607
     */
608
    private function twosComplement(string $number) : string
609
    {
610
        $xor = \str_repeat("\xff", \strlen($number));
611
 
612
        $number ^= $xor;
613
 
614
        for ($i = \strlen($number) - 1; $i >= 0; $i--) {
615
            $byte = \ord($number[$i]);
616
 
617
            if (++$byte !== 256) {
618
                $number[$i] = \chr($byte);
619
                break;
620
            }
621
 
622
            $number[$i] = "\x00";
623
 
624
            if ($i === 0) {
625
                $number = "\x01" . $number;
626
            }
627
        }
628
 
629
        return $number;
630
    }
631
 
632
    /**
633
     * Converts a decimal number to a binary string.
634
     *
635
     * @param string $number The number to convert, positive or zero, only digits.
636
     */
637
    private function toBinary(string $number) : string
638
    {
639
        $result = '';
640
 
641
        while ($number !== '0') {
642
            [$number, $remainder] = $this->divQR($number, '256');
643
            $result .= \chr((int) $remainder);
644
        }
645
 
646
        return \strrev($result);
647
    }
648
 
649
    /**
650
     * Returns the positive decimal representation of a binary number.
651
     *
652
     * @param string $bytes The bytes representing the number.
653
     */
654
    private function toDecimal(string $bytes) : string
655
    {
656
        $result = '0';
657
        $power = '1';
658
 
659
        for ($i = \strlen($bytes) - 1; $i >= 0; $i--) {
660
            $index = \ord($bytes[$i]);
661
 
662
            if ($index !== 0) {
663
                $result = $this->add($result, ($index === 1)
664
                    ? $power
665
                    : $this->mul($power, (string) $index)
666
                );
667
            }
668
 
669
            if ($i !== 0) {
670
                $power = $this->mul($power, '256');
671
            }
672
        }
673
 
674
        return $result;
675
    }
676
}