| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Brick\Math\Internal\Calculator; |
| 6 |
|
| 7 |
use Brick\Math\Internal\Calculator; |
| 8 |
|
| 9 |
/** |
| 10 |
* Calculator implementation built around the bcmath library. |
| 11 |
* |
| 12 |
* @internal |
| 13 |
* |
| 14 |
* @psalm-immutable |
| 15 |
*/ |
| 16 |
class BcMathCalculator extends Calculator |
| 17 |
{ |
| 18 |
/** |
| 19 |
* {@inheritdoc} |
| 20 |
*/ |
| 21 |
public function add(string $a, string $b) : string |
| 22 |
{ |
| 23 |
return \bcadd($a, $b, 0); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* {@inheritdoc} |
| 28 |
*/ |
| 29 |
public function sub(string $a, string $b) : string |
| 30 |
{ |
| 31 |
return \bcsub($a, $b, 0); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* {@inheritdoc} |
| 36 |
*/ |
| 37 |
public function mul(string $a, string $b) : string |
| 38 |
{ |
| 39 |
return \bcmul($a, $b, 0); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* {@inheritdoc} |
| 44 |
* |
| 45 |
* @psalm-suppress InvalidNullableReturnType |
| 46 |
* @psalm-suppress NullableReturnStatement |
| 47 |
*/ |
| 48 |
public function divQ(string $a, string $b) : string |
| 49 |
{ |
| 50 |
return \bcdiv($a, $b, 0); |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* {@inheritdoc} |
| 55 |
* |
| 56 |
* @psalm-suppress InvalidNullableReturnType |
| 57 |
* @psalm-suppress NullableReturnStatement |
| 58 |
*/ |
| 59 |
public function divR(string $a, string $b) : string |
| 60 |
{ |
| 61 |
if (version_compare(PHP_VERSION, '7.2') >= 0) { |
| 62 |
return \bcmod($a, $b, 0); |
| 63 |
} |
| 64 |
|
| 65 |
return \bcmod($a, $b); |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* {@inheritdoc} |
| 70 |
*/ |
| 71 |
public function divQR(string $a, string $b) : array |
| 72 |
{ |
| 73 |
$q = \bcdiv($a, $b, 0); |
| 74 |
|
| 75 |
if (version_compare(PHP_VERSION, '7.2') >= 0) { |
| 76 |
$r = \bcmod($a, $b, 0); |
| 77 |
} else { |
| 78 |
$r = \bcmod($a, $b); |
| 79 |
} |
| 80 |
|
| 81 |
assert($q !== null); |
| 82 |
assert($r !== null); |
| 83 |
|
| 84 |
return [$q, $r]; |
| 85 |
} |
| 86 |
|
| 87 |
/** |
| 88 |
* {@inheritdoc} |
| 89 |
*/ |
| 90 |
public function pow(string $a, int $e) : string |
| 91 |
{ |
| 92 |
return \bcpow($a, (string) $e, 0); |
| 93 |
} |
| 94 |
|
| 95 |
/** |
| 96 |
* {@inheritdoc} |
| 97 |
* |
| 98 |
* @psalm-suppress InvalidNullableReturnType |
| 99 |
* @psalm-suppress NullableReturnStatement |
| 100 |
*/ |
| 101 |
public function modPow(string $base, string $exp, string $mod) : string |
| 102 |
{ |
| 103 |
return \bcpowmod($base, $exp, $mod, 0); |
| 104 |
} |
| 105 |
|
| 106 |
/** |
| 107 |
* {@inheritDoc} |
| 108 |
* |
| 109 |
* @psalm-suppress NullableReturnStatement |
| 110 |
* @psalm-suppress InvalidNullableReturnType |
| 111 |
*/ |
| 112 |
public function sqrt(string $n) : string |
| 113 |
{ |
| 114 |
return \bcsqrt($n, 0); |
| 115 |
} |
| 116 |
} |
| 117 |
|