Debian Codegraph @

lib/3rdParty/composer/brick/math/src/BigNumber.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Brick\Math;
6
7 use Brick\Math\Exception\DivisionByZeroException;
8 use Brick\Math\Exception\MathException;
9 use Brick\Math\Exception\NumberFormatException;
10 use Brick\Math\Exception\RoundingNecessaryException;
11 use Override;
12
13 /**
14 * Common interface for arbitrary-precision rational numbers.
15 *
16 * @psalm-immutable
17 */
18 abstract class BigNumber implements \JsonSerializable
19 {
20 /**
21 * The regular expression used to parse integer or decimal numbers.
22 */
23 private const PARSE_REGEXP_NUMERICAL =
24 '/^' .
25 '(?<sign>[\-\+])?' .
26 '(?<integral>[0-9]+)?' .
27 '(?<point>\.)?' .
28 '(?<fractional>[0-9]+)?' .
29 '(?:[eE](?<exponent>[\-\+]?[0-9]+))?' .
30 '$/';
31
32 /**
33 * The regular expression used to parse rational numbers.
34 */
35 private const PARSE_REGEXP_RATIONAL =
36 '/^' .
37 '(?<sign>[\-\+])?' .
38 '(?<numerator>[0-9]+)' .
39 '\/?' .
40 '(?<denominator>[0-9]+)' .
41 '$/';
42
43 /**
44 * Creates a BigNumber of the given value.
45 *
46 * The concrete return type is dependent on the given value, with the following rules:
47 *
48 * - BigNumber instances are returned as is
49 * - integer numbers are returned as BigInteger
50 * - floating point numbers are converted to a string then parsed as such
51 * - strings containing a `/` character are returned as BigRational
52 * - strings containing a `.` character or using an exponential notation are returned as BigDecimal
53 * - strings containing only digits with an optional leading `+` or `-` sign are returned as BigInteger
54 *
55 * @throws NumberFormatException If the format of the number is not valid.
56 * @throws DivisionByZeroException If the value represents a rational number with a denominator of zero.
57 * @throws RoundingNecessaryException If the value cannot be converted to an instance of the subclass without rounding.
58 *
59 * @psalm-pure
60 */
61 final public static function of(BigNumber|int|float|string $value) : static
62 {
63 $value = self::_of($value);
64
65 if (static::class === BigNumber::class) {
66 // https://github.com/vimeo/psalm/issues/10309
67 assert($value instanceof static);
68
69 return $value;
70 }
71
72 return static::from($value);
73 }
74
75 /**
76 * @throws NumberFormatException If the format of the number is not valid.
77 * @throws DivisionByZeroException If the value represents a rational number with a denominator of zero.
78 *
79 * @psalm-pure
80 */
81 private static function _of(BigNumber|int|float|string $value) : BigNumber
82 {
83 if ($value instanceof BigNumber) {
84 return $value;
85 }
86
87 if (\is_int($value)) {
88 return new BigInteger((string) $value);
89 }
90
91 if (is_float($value)) {
92 $value = (string) $value;
93 }
94
95 if (str_contains($value, '/')) {
96 // Rational number
97 if (\preg_match(self::PARSE_REGEXP_RATIONAL, $value, $matches, PREG_UNMATCHED_AS_NULL) !== 1) {
98 throw NumberFormatException::invalidFormat($value);
99 }
100
101 $sign = $matches['sign'];
102 $numerator = $matches['numerator'];
103 $denominator = $matches['denominator'];
104
105 assert($numerator !== null);
106 assert($denominator !== null);
107
108 $numerator = self::cleanUp($sign, $numerator);
109 $denominator = self::cleanUp(null, $denominator);
110
111 if ($denominator === '0') {
112 throw DivisionByZeroException::denominatorMustNotBeZero();
113 }
114
115 return new BigRational(
116 new BigInteger($numerator),
117 new BigInteger($denominator),
118 false
119 );
120 } else {
121 // Integer or decimal number
122 if (\preg_match(self::PARSE_REGEXP_NUMERICAL, $value, $matches, PREG_UNMATCHED_AS_NULL) !== 1) {
123 throw NumberFormatException::invalidFormat($value);
124 }
125
126 $sign = $matches['sign'];
127 $point = $matches['point'];
128 $integral = $matches['integral'];
129 $fractional = $matches['fractional'];
130 $exponent = $matches['exponent'];
131
132 if ($integral === null && $fractional === null) {
133 throw NumberFormatException::invalidFormat($value);
134 }
135
136 if ($integral === null) {
137 $integral = '0';
138 }
139
140 if ($point !== null || $exponent !== null) {
141 $fractional = ($fractional ?? '');
142 $exponent = ($exponent !== null) ? (int)$exponent : 0;
143
144 if ($exponent === PHP_INT_MIN || $exponent === PHP_INT_MAX) {
145 throw new NumberFormatException('Exponent too large.');
146 }
147
148 $unscaledValue = self::cleanUp($sign, $integral . $fractional);
149
150 $scale = \strlen($fractional) - $exponent;
151
152 if ($scale < 0) {
153 if ($unscaledValue !== '0') {
154 $unscaledValue .= \str_repeat('0', -$scale);
155 }
156 $scale = 0;
157 }
158
159 return new BigDecimal($unscaledValue, $scale);
160 }
161
162 $integral = self::cleanUp($sign, $integral);
163
164 return new BigInteger($integral);
165 }
166 }
167
168 /**
169 * Overridden by subclasses to convert a BigNumber to an instance of the subclass.
170 *
171 * @throws RoundingNecessaryException If the value cannot be converted.
172 *
173 * @psalm-pure
174 */
175 abstract protected static function from(BigNumber $number): static;
176
177 /**
178 * Proxy method to access BigInteger's protected constructor from sibling classes.
179 *
180 * @internal
181 * @psalm-pure
182 */
183 final protected function newBigInteger(string $value) : BigInteger
184 {
185 return new BigInteger($value);
186 }
187
188 /**
189 * Proxy method to access BigDecimal's protected constructor from sibling classes.
190 *
191 * @internal
192 * @psalm-pure
193 */
194 final protected function newBigDecimal(string $value, int $scale = 0) : BigDecimal
195 {
196 return new BigDecimal($value, $scale);
197 }
198
199 /**
200 * Proxy method to access BigRational's protected constructor from sibling classes.
201 *
202 * @internal
203 * @psalm-pure
204 */
205 final protected function newBigRational(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator) : BigRational
206 {
207 return new BigRational($numerator, $denominator, $checkDenominator);
208 }
209
210 /**
211 * Returns the minimum of the given values.
212 *
213 * @param BigNumber|int|float|string ...$values The numbers to compare. All the numbers need to be convertible
214 * to an instance of the class this method is called on.
215 *
216 * @throws \InvalidArgumentException If no values are given.
217 * @throws MathException If an argument is not valid.
218 *
219 * @psalm-pure
220 */
221 final public static function min(BigNumber|int|float|string ...$values) : static
222 {
223 $min = null;
224
225 foreach ($values as $value) {
226 $value = static::of($value);
227
228 if ($min === null || $value->isLessThan($min)) {
229 $min = $value;
230 }
231 }
232
233 if ($min === null) {
234 throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
235 }
236
237 return $min;
238 }
239
240 /**
241 * Returns the maximum of the given values.
242 *
243 * @param BigNumber|int|float|string ...$values The numbers to compare. All the numbers need to be convertible
244 * to an instance of the class this method is called on.
245 *
246 * @throws \InvalidArgumentException If no values are given.
247 * @throws MathException If an argument is not valid.
248 *
249 * @psalm-pure
250 */
251 final public static function max(BigNumber|int|float|string ...$values) : static
252 {
253 $max = null;
254
255 foreach ($values as $value) {
256 $value = static::of($value);
257
258 if ($max === null || $value->isGreaterThan($max)) {
259 $max = $value;
260 }
261 }
262
263 if ($max === null) {
264 throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
265 }
266
267 return $max;
268 }
269
270 /**
271 * Returns the sum of the given values.
272 *
273 * @param BigNumber|int|float|string ...$values The numbers to add. All the numbers need to be convertible
274 * to an instance of the class this method is called on.
275 *
276 * @throws \InvalidArgumentException If no values are given.
277 * @throws MathException If an argument is not valid.
278 *
279 * @psalm-pure
280 */
281 final public static function sum(BigNumber|int|float|string ...$values) : static
282 {
283 /** @var static|null $sum */
284 $sum = null;
285
286 foreach ($values as $value) {
287 $value = static::of($value);
288
289 $sum = $sum === null ? $value : self::add($sum, $value);
290 }
291
292 if ($sum === null) {
293 throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
294 }
295
296 return $sum;
297 }
298
299 /**
300 * Adds two BigNumber instances in the correct order to avoid a RoundingNecessaryException.
301 *
302 * @todo This could be better resolved by creating an abstract protected method in BigNumber, and leaving to
303 * concrete classes the responsibility to perform the addition themselves or delegate it to the given number,
304 * depending on their ability to perform the operation. This will also require a version bump because we're
305 * potentially breaking custom BigNumber implementations (if any...)
306 *
307 * @psalm-pure
308 */
309 private static function add(BigNumber $a, BigNumber $b) : BigNumber
310 {
311 if ($a instanceof BigRational) {
312 return $a->plus($b);
313 }
314
315 if ($b instanceof BigRational) {
316 return $b->plus($a);
317 }
318
319 if ($a instanceof BigDecimal) {
320 return $a->plus($b);
321 }
322
323 if ($b instanceof BigDecimal) {
324 return $b->plus($a);
325 }
326
327 /** @var BigInteger $a */
328
329 return $a->plus($b);
330 }
331
332 /**
333 * Removes optional leading zeros and applies sign.
334 *
335 * @param string|null $sign The sign, '+' or '-', optional. Null is allowed for convenience and treated as '+'.
336 * @param string $number The number, validated as a non-empty string of digits.
337 *
338 * @psalm-pure
339 */
340 private static function cleanUp(string|null $sign, string $number) : string
341 {
342 $number = \ltrim($number, '0');
343
344 if ($number === '') {
345 return '0';
346 }
347
348 return $sign === '-' ? '-' . $number : $number;
349 }
350
351 /**
352 * Checks if this number is equal to the given one.
353 */
354 final public function isEqualTo(BigNumber|int|float|string $that) : bool
355 {
356 return $this->compareTo($that) === 0;
357 }
358
359 /**
360 * Checks if this number is strictly lower than the given one.
361 */
362 final public function isLessThan(BigNumber|int|float|string $that) : bool
363 {
364 return $this->compareTo($that) < 0;
365 }
366
367 /**
368 * Checks if this number is lower than or equal to the given one.
369 */
370 final public function isLessThanOrEqualTo(BigNumber|int|float|string $that) : bool
371 {
372 return $this->compareTo($that) <= 0;
373 }
374
375 /**
376 * Checks if this number is strictly greater than the given one.
377 */
378 final public function isGreaterThan(BigNumber|int|float|string $that) : bool
379 {
380 return $this->compareTo($that) > 0;
381 }
382
383 /**
384 * Checks if this number is greater than or equal to the given one.
385 */
386 final public function isGreaterThanOrEqualTo(BigNumber|int|float|string $that) : bool
387 {
388 return $this->compareTo($that) >= 0;
389 }
390
391 /**
392 * Checks if this number equals zero.
393 */
394 final public function isZero() : bool
395 {
396 return $this->getSign() === 0;
397 }
398
399 /**
400 * Checks if this number is strictly negative.
401 */
402 final public function isNegative() : bool
403 {
404 return $this->getSign() < 0;
405 }
406
407 /**
408 * Checks if this number is negative or zero.
409 */
410 final public function isNegativeOrZero() : bool
411 {
412 return $this->getSign() <= 0;
413 }
414
415 /**
416 * Checks if this number is strictly positive.
417 */
418 final public function isPositive() : bool
419 {
420 return $this->getSign() > 0;
421 }
422
423 /**
424 * Checks if this number is positive or zero.
425 */
426 final public function isPositiveOrZero() : bool
427 {
428 return $this->getSign() >= 0;
429 }
430
431 /**
432 * Returns the sign of this number.
433 *
434 * @psalm-return -1|0|1
435 *
436 * @return int -1 if the number is negative, 0 if zero, 1 if positive.
437 */
438 abstract public function getSign() : int;
439
440 /**
441 * Compares this number to the given one.
442 *
443 * @psalm-return -1|0|1
444 *
445 * @return int -1 if `$this` is lower than, 0 if equal to, 1 if greater than `$that`.
446 *
447 * @throws MathException If the number is not valid.
448 */
449 abstract public function compareTo(BigNumber|int|float|string $that) : int;
450
451 /**
452 * Converts this number to a BigInteger.
453 *
454 * @throws RoundingNecessaryException If this number cannot be converted to a BigInteger without rounding.
455 */
456 abstract public function toBigInteger() : BigInteger;
457
458 /**
459 * Converts this number to a BigDecimal.
460 *
461 * @throws RoundingNecessaryException If this number cannot be converted to a BigDecimal without rounding.
462 */
463 abstract public function toBigDecimal() : BigDecimal;
464
465 /**
466 * Converts this number to a BigRational.
467 */
468 abstract public function toBigRational() : BigRational;
469
470 /**
471 * Converts this number to a BigDecimal with the given scale, using rounding if necessary.
472 *
473 * @param int $scale The scale of the resulting `BigDecimal`.
474 * @param RoundingMode $roundingMode An optional rounding mode, defaults to UNNECESSARY.
475 *
476 * @throws RoundingNecessaryException If this number cannot be converted to the given scale without rounding.
477 * This only applies when RoundingMode::UNNECESSARY is used.
478 */
479 abstract public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal;
480
481 /**
482 * Returns the exact value of this number as a native integer.
483 *
484 * If this number cannot be converted to a native integer without losing precision, an exception is thrown.
485 * Note that the acceptable range for an integer depends on the platform and differs for 32-bit and 64-bit.
486 *
487 * @throws MathException If this number cannot be exactly converted to a native integer.
488 */
489 abstract public function toInt() : int;
490
491 /**
492 * Returns an approximation of this number as a floating-point value.
493 *
494 * Note that this method can discard information as the precision of a floating-point value
495 * is inherently limited.
496 *
497 * If the number is greater than the largest representable floating point number, positive infinity is returned.
498 * If the number is less than the smallest representable floating point number, negative infinity is returned.
499 */
500 abstract public function toFloat() : float;
501
502 /**
503 * Returns a string representation of this number.
504 *
505 * The output of this method can be parsed by the `of()` factory method;
506 * this will yield an object equal to this one, without any information loss.
507 */
508 abstract public function __toString() : string;
509
510 #[Override]
511 final public function jsonSerialize() : string
512 {
513 return $this->__toString();
514 }
515 }