Debian Codegraph @

include/fast_float/bigint.h

raw
1 #ifndef FASTFLOAT_BIGINT_H
2 #define FASTFLOAT_BIGINT_H
3
4 #include <algorithm>
5 #include <cstdint>
6 #include <climits>
7 #include <cstring>
8
9 #include "float_common.h"
10
11 namespace fast_float {
12
13 // the limb width: we want efficient multiplication of double the bits in
14 // limb, or for 64-bit limbs, at least 64-bit multiplication where we can
15 // extract the high and low parts efficiently. this is every 64-bit
16 // architecture except for sparc, which emulates 128-bit multiplication.
17 // we might have platforms where `CHAR_BIT` is not 8, so let's avoid
18 // doing `8 * sizeof(limb)`.
19 #if defined(FASTFLOAT_64BIT) && !defined(__sparc)
20 #define FASTFLOAT_64BIT_LIMB 1
21 typedef uint64_t limb;
22 constexpr size_t limb_bits = 64;
23 #else
24 #define FASTFLOAT_32BIT_LIMB
25 typedef uint32_t limb;
26 constexpr size_t limb_bits = 32;
27 #endif
28
29 typedef span<limb> limb_span;
30
31 // number of bits in a bigint. this needs to be at least the number
32 // of bits required to store the largest bigint, which is
33 // `log2(10**(digits + max_exp))`, or `log2(10**(767 + 342))`, or
34 // ~3600 bits, so we round to 4000.
35 constexpr size_t bigint_bits = 4000;
36 constexpr size_t bigint_limbs = bigint_bits / limb_bits;
37
38 // vector-like type that is allocated on the stack. the entire
39 // buffer is pre-allocated, and only the length changes.
40 template <uint16_t size> struct stackvec {
41 limb data[size];
42 // we never need more than 150 limbs
43 uint16_t length{0};
44
45 stackvec() = default;
46 stackvec(stackvec const &) = delete;
47 stackvec &operator=(stackvec const &) = delete;
48 stackvec(stackvec &&) = delete;
49 stackvec &operator=(stackvec &&other) = delete;
50
51 // create stack vector from existing limb span.
52 FASTFLOAT_CONSTEXPR20 stackvec(limb_span s) {
53 FASTFLOAT_ASSERT(try_extend(s));
54 }
55
56 FASTFLOAT_CONSTEXPR14 limb &operator[](size_t index) noexcept {
57 FASTFLOAT_DEBUG_ASSERT(index < length);
58 return data[index];
59 }
60
61 FASTFLOAT_CONSTEXPR14 const limb &operator[](size_t index) const noexcept {
62 FASTFLOAT_DEBUG_ASSERT(index < length);
63 return data[index];
64 }
65
66 // index from the end of the container
67 FASTFLOAT_CONSTEXPR14 const limb &rindex(size_t index) const noexcept {
68 FASTFLOAT_DEBUG_ASSERT(index < length);
69 size_t rindex = length - index - 1;
70 return data[rindex];
71 }
72
73 // set the length, without bounds checking.
74 FASTFLOAT_CONSTEXPR14 void set_len(size_t len) noexcept {
75 length = uint16_t(len);
76 }
77
78 constexpr size_t len() const noexcept { return length; }
79
80 constexpr bool is_empty() const noexcept { return length == 0; }
81
82 constexpr size_t capacity() const noexcept { return size; }
83
84 // append item to vector, without bounds checking
85 FASTFLOAT_CONSTEXPR14 void push_unchecked(limb value) noexcept {
86 data[length] = value;
87 length++;
88 }
89
90 // append item to vector, returning if item was added
91 FASTFLOAT_CONSTEXPR14 bool try_push(limb value) noexcept {
92 if (len() < capacity()) {
93 push_unchecked(value);
94 return true;
95 } else {
96 return false;
97 }
98 }
99
100 // add items to the vector, from a span, without bounds checking
101 FASTFLOAT_CONSTEXPR20 void extend_unchecked(limb_span s) noexcept {
102 limb *ptr = data + length;
103 std::copy_n(s.ptr, s.len(), ptr);
104 set_len(len() + s.len());
105 }
106
107 // try to add items to the vector, returning if items were added
108 FASTFLOAT_CONSTEXPR20 bool try_extend(limb_span s) noexcept {
109 if (len() + s.len() <= capacity()) {
110 extend_unchecked(s);
111 return true;
112 } else {
113 return false;
114 }
115 }
116
117 // resize the vector, without bounds checking
118 // if the new size is longer than the vector, assign value to each
119 // appended item.
120 FASTFLOAT_CONSTEXPR20
121 void resize_unchecked(size_t new_len, limb value) noexcept {
122 if (new_len > len()) {
123 size_t count = new_len - len();
124 limb *first = data + len();
125 limb *last = first + count;
126 ::std::fill(first, last, value);
127 set_len(new_len);
128 } else {
129 set_len(new_len);
130 }
131 }
132
133 // try to resize the vector, returning if the vector was resized.
134 FASTFLOAT_CONSTEXPR20 bool try_resize(size_t new_len, limb value) noexcept {
135 if (new_len > capacity()) {
136 return false;
137 } else {
138 resize_unchecked(new_len, value);
139 return true;
140 }
141 }
142
143 // check if any limbs are non-zero after the given index.
144 // this needs to be done in reverse order, since the index
145 // is relative to the most significant limbs.
146 FASTFLOAT_CONSTEXPR14 bool nonzero(size_t index) const noexcept {
147 while (index < len()) {
148 if (rindex(index) != 0) {
149 return true;
150 }
151 index++;
152 }
153 return false;
154 }
155
156 // normalize the big integer, so most-significant zero limbs are removed.
157 FASTFLOAT_CONSTEXPR14 void normalize() noexcept {
158 while (len() > 0 && rindex(0) == 0) {
159 length--;
160 }
161 }
162 };
163
164 fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint64_t
165 empty_hi64(bool &truncated) noexcept {
166 truncated = false;
167 return 0;
168 }
169
170 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t
171 uint64_hi64(uint64_t r0, bool &truncated) noexcept {
172 truncated = false;
173 int shl = leading_zeroes(r0);
174 return r0 << shl;
175 }
176
177 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t
178 uint64_hi64(uint64_t r0, uint64_t r1, bool &truncated) noexcept {
179 int shl = leading_zeroes(r0);
180 if (shl == 0) {
181 truncated = r1 != 0;
182 return r0;
183 } else {
184 int shr = 64 - shl;
185 truncated = (r1 << shl) != 0;
186 return (r0 << shl) | (r1 >> shr);
187 }
188 }
189
190 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t
191 uint32_hi64(uint32_t r0, bool &truncated) noexcept {
192 return uint64_hi64(r0, truncated);
193 }
194
195 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t
196 uint32_hi64(uint32_t r0, uint32_t r1, bool &truncated) noexcept {
197 uint64_t x0 = r0;
198 uint64_t x1 = r1;
199 return uint64_hi64((x0 << 32) | x1, truncated);
200 }
201
202 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t
203 uint32_hi64(uint32_t r0, uint32_t r1, uint32_t r2, bool &truncated) noexcept {
204 uint64_t x0 = r0;
205 uint64_t x1 = r1;
206 uint64_t x2 = r2;
207 return uint64_hi64(x0, (x1 << 32) | x2, truncated);
208 }
209
210 // add two small integers, checking for overflow.
211 // we want an efficient operation. for msvc, where
212 // we don't have built-in intrinsics, this is still
213 // pretty fast.
214 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 limb
215 scalar_add(limb x, limb y, bool &overflow) noexcept {
216 limb z;
217 // gcc and clang
218 #if defined(__has_builtin)
219 #if __has_builtin(__builtin_add_overflow)
220 if (!cpp20_and_in_constexpr()) {
221 overflow = __builtin_add_overflow(x, y, &z);
222 return z;
223 }
224 #endif
225 #endif
226
227 // generic, this still optimizes correctly on MSVC.
228 z = x + y;
229 overflow = z < x;
230 return z;
231 }
232
233 // multiply two small integers, getting both the high and low bits.
234 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 limb
235 scalar_mul(limb x, limb y, limb &carry) noexcept {
236 #ifdef FASTFLOAT_64BIT_LIMB
237 #if defined(__SIZEOF_INT128__)
238 // GCC and clang both define it as an extension.
239 __uint128_t z = __uint128_t(x) * __uint128_t(y) + __uint128_t(carry);
240 carry = limb(z >> limb_bits);
241 return limb(z);
242 #else
243 // fallback, no native 128-bit integer multiplication with carry.
244 // on msvc, this optimizes identically, somehow.
245 value128 z = full_multiplication(x, y);
246 bool overflow;
247 z.low = scalar_add(z.low, carry, overflow);
248 z.high += uint64_t(overflow); // cannot overflow
249 carry = z.high;
250 return z.low;
251 #endif
252 #else
253 uint64_t z = uint64_t(x) * uint64_t(y) + uint64_t(carry);
254 carry = limb(z >> limb_bits);
255 return limb(z);
256 #endif
257 }
258
259 // add scalar value to bigint starting from offset.
260 // used in grade school multiplication
261 template <uint16_t size>
262 inline FASTFLOAT_CONSTEXPR20 bool small_add_from(stackvec<size> &vec, limb y,
263 size_t start) noexcept {
264 size_t index = start;
265 limb carry = y;
266 bool overflow;
267 while (carry != 0 && index < vec.len()) {
268 vec[index] = scalar_add(vec[index], carry, overflow);
269 carry = limb(overflow);
270 index += 1;
271 }
272 if (carry != 0) {
273 FASTFLOAT_TRY(vec.try_push(carry));
274 }
275 return true;
276 }
277
278 // add scalar value to bigint.
279 template <uint16_t size>
280 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool
281 small_add(stackvec<size> &vec, limb y) noexcept {
282 return small_add_from(vec, y, 0);
283 }
284
285 // multiply bigint by scalar value.
286 template <uint16_t size>
287 inline FASTFLOAT_CONSTEXPR20 bool small_mul(stackvec<size> &vec,
288 limb y) noexcept {
289 limb carry = 0;
290 for (size_t index = 0; index < vec.len(); index++) {
291 vec[index] = scalar_mul(vec[index], y, carry);
292 }
293 if (carry != 0) {
294 FASTFLOAT_TRY(vec.try_push(carry));
295 }
296 return true;
297 }
298
299 // add bigint to bigint starting from index.
300 // used in grade school multiplication
301 template <uint16_t size>
302 FASTFLOAT_CONSTEXPR20 bool large_add_from(stackvec<size> &x, limb_span y,
303 size_t start) noexcept {
304 // the effective x buffer is from `xstart..x.len()`, so exit early
305 // if we can't get that current range.
306 if (x.len() < start || y.len() > x.len() - start) {
307 FASTFLOAT_TRY(x.try_resize(y.len() + start, 0));
308 }
309
310 bool carry = false;
311 for (size_t index = 0; index < y.len(); index++) {
312 limb xi = x[index + start];
313 limb yi = y[index];
314 bool c1 = false;
315 bool c2 = false;
316 xi = scalar_add(xi, yi, c1);
317 if (carry) {
318 xi = scalar_add(xi, 1, c2);
319 }
320 x[index + start] = xi;
321 carry = c1 | c2;
322 }
323
324 // handle overflow
325 if (carry) {
326 FASTFLOAT_TRY(small_add_from(x, 1, y.len() + start));
327 }
328 return true;
329 }
330
331 // add bigint to bigint.
332 template <uint16_t size>
333 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool
334 large_add_from(stackvec<size> &x, limb_span y) noexcept {
335 return large_add_from(x, y, 0);
336 }
337
338 // grade-school multiplication algorithm
339 template <uint16_t size>
340 FASTFLOAT_CONSTEXPR20 bool long_mul(stackvec<size> &x, limb_span y) noexcept {
341 limb_span xs = limb_span(x.data, x.len());
342 stackvec<size> z(xs);
343 limb_span zs = limb_span(z.data, z.len());
344
345 if (y.len() != 0) {
346 limb y0 = y[0];
347 FASTFLOAT_TRY(small_mul(x, y0));
348 for (size_t index = 1; index < y.len(); index++) {
349 limb yi = y[index];
350 stackvec<size> zi;
351 if (yi != 0) {
352 // re-use the same buffer throughout
353 zi.set_len(0);
354 FASTFLOAT_TRY(zi.try_extend(zs));
355 FASTFLOAT_TRY(small_mul(zi, yi));
356 limb_span zis = limb_span(zi.data, zi.len());
357 FASTFLOAT_TRY(large_add_from(x, zis, index));
358 }
359 }
360 }
361
362 x.normalize();
363 return true;
364 }
365
366 // grade-school multiplication algorithm
367 template <uint16_t size>
368 FASTFLOAT_CONSTEXPR20 bool large_mul(stackvec<size> &x, limb_span y) noexcept {
369 if (y.len() == 1) {
370 FASTFLOAT_TRY(small_mul(x, y[0]));
371 } else {
372 FASTFLOAT_TRY(long_mul(x, y));
373 }
374 return true;
375 }
376
377 template <typename = void> struct pow5_tables {
378 static constexpr uint32_t large_step = 135;
379 static constexpr uint64_t small_power_of_5[] = {
380 1UL,
381 5UL,
382 25UL,
383 125UL,
384 625UL,
385 3125UL,
386 15625UL,
387 78125UL,
388 390625UL,
389 1953125UL,
390 9765625UL,
391 48828125UL,
392 244140625UL,
393 1220703125UL,
394 6103515625UL,
395 30517578125UL,
396 152587890625UL,
397 762939453125UL,
398 3814697265625UL,
399 19073486328125UL,
400 95367431640625UL,
401 476837158203125UL,
402 2384185791015625UL,
403 11920928955078125UL,
404 59604644775390625UL,
405 298023223876953125UL,
406 1490116119384765625UL,
407 7450580596923828125UL,
408 };
409 #ifdef FASTFLOAT_64BIT_LIMB
410 constexpr static limb large_power_of_5[] = {
411 1414648277510068013UL, 9180637584431281687UL, 4539964771860779200UL,
412 10482974169319127550UL, 198276706040285095UL};
413 #else
414 constexpr static limb large_power_of_5[] = {
415 4279965485U, 329373468U, 4020270615U, 2137533757U, 4287402176U,
416 1057042919U, 1071430142U, 2440757623U, 381945767U, 46164893U};
417 #endif
418 };
419
420 #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE
421
422 template <typename T> constexpr uint32_t pow5_tables<T>::large_step;
423
424 template <typename T> constexpr uint64_t pow5_tables<T>::small_power_of_5[];
425
426 template <typename T> constexpr limb pow5_tables<T>::large_power_of_5[];
427
428 #endif
429
430 // big integer type. implements a small subset of big integer
431 // arithmetic, using simple algorithms since asymptotically
432 // faster algorithms are slower for a small number of limbs.
433 // all operations assume the big-integer is normalized.
434 struct bigint : pow5_tables<> {
435 // storage of the limbs, in little-endian order.
436 stackvec<bigint_limbs> vec;
437
438 FASTFLOAT_CONSTEXPR20 bigint() : vec() {}
439
440 bigint(bigint const &) = delete;
441 bigint &operator=(bigint const &) = delete;
442 bigint(bigint &&) = delete;
443 bigint &operator=(bigint &&other) = delete;
444
445 FASTFLOAT_CONSTEXPR20 bigint(uint64_t value) : vec() {
446 #ifdef FASTFLOAT_64BIT_LIMB
447 vec.push_unchecked(value);
448 #else
449 vec.push_unchecked(uint32_t(value));
450 vec.push_unchecked(uint32_t(value >> 32));
451 #endif
452 vec.normalize();
453 }
454
455 // get the high 64 bits from the vector, and if bits were truncated.
456 // this is to get the significant digits for the float.
457 FASTFLOAT_CONSTEXPR20 uint64_t hi64(bool &truncated) const noexcept {
458 #ifdef FASTFLOAT_64BIT_LIMB
459 if (vec.len() == 0) {
460 return empty_hi64(truncated);
461 } else if (vec.len() == 1) {
462 return uint64_hi64(vec.rindex(0), truncated);
463 } else {
464 uint64_t result = uint64_hi64(vec.rindex(0), vec.rindex(1), truncated);
465 truncated |= vec.nonzero(2);
466 return result;
467 }
468 #else
469 if (vec.len() == 0) {
470 return empty_hi64(truncated);
471 } else if (vec.len() == 1) {
472 return uint32_hi64(vec.rindex(0), truncated);
473 } else if (vec.len() == 2) {
474 return uint32_hi64(vec.rindex(0), vec.rindex(1), truncated);
475 } else {
476 uint64_t result =
477 uint32_hi64(vec.rindex(0), vec.rindex(1), vec.rindex(2), truncated);
478 truncated |= vec.nonzero(3);
479 return result;
480 }
481 #endif
482 }
483
484 // compare two big integers, returning the large value.
485 // assumes both are normalized. if the return value is
486 // negative, other is larger, if the return value is
487 // positive, this is larger, otherwise they are equal.
488 // the limbs are stored in little-endian order, so we
489 // must compare the limbs in ever order.
490 FASTFLOAT_CONSTEXPR20 int compare(bigint const &other) const noexcept {
491 if (vec.len() > other.vec.len()) {
492 return 1;
493 } else if (vec.len() < other.vec.len()) {
494 return -1;
495 } else {
496 for (size_t index = vec.len(); index > 0; index--) {
497 limb xi = vec[index - 1];
498 limb yi = other.vec[index - 1];
499 if (xi > yi) {
500 return 1;
501 } else if (xi < yi) {
502 return -1;
503 }
504 }
505 return 0;
506 }
507 }
508
509 // shift left each limb n bits, carrying over to the new limb
510 // returns true if we were able to shift all the digits.
511 FASTFLOAT_CONSTEXPR20 bool shl_bits(size_t n) noexcept {
512 // Internally, for each item, we shift left by n, and add the previous
513 // right shifted limb-bits.
514 // For example, we transform (for u8) shifted left 2, to:
515 // b10100100 b01000010
516 // b10 b10010001 b00001000
517 FASTFLOAT_DEBUG_ASSERT(n != 0);
518 FASTFLOAT_DEBUG_ASSERT(n < sizeof(limb) * 8);
519
520 size_t shl = n;
521 size_t shr = limb_bits - shl;
522 limb prev = 0;
523 for (size_t index = 0; index < vec.len(); index++) {
524 limb xi = vec[index];
525 vec[index] = (xi << shl) | (prev >> shr);
526 prev = xi;
527 }
528
529 limb carry = prev >> shr;
530 if (carry != 0) {
531 return vec.try_push(carry);
532 }
533 return true;
534 }
535
536 // move the limbs left by `n` limbs.
537 FASTFLOAT_CONSTEXPR20 bool shl_limbs(size_t n) noexcept {
538 FASTFLOAT_DEBUG_ASSERT(n != 0);
539 if (n + vec.len() > vec.capacity()) {
540 return false;
541 } else if (!vec.is_empty()) {
542 // move limbs
543 limb *dst = vec.data + n;
544 limb const *src = vec.data;
545 std::copy_backward(src, src + vec.len(), dst + vec.len());
546 // fill in empty limbs
547 limb *first = vec.data;
548 limb *last = first + n;
549 ::std::fill(first, last, 0);
550 vec.set_len(n + vec.len());
551 return true;
552 } else {
553 return true;
554 }
555 }
556
557 // move the limbs left by `n` bits.
558 FASTFLOAT_CONSTEXPR20 bool shl(size_t n) noexcept {
559 size_t rem = n % limb_bits;
560 size_t div = n / limb_bits;
561 if (rem != 0) {
562 FASTFLOAT_TRY(shl_bits(rem));
563 }
564 if (div != 0) {
565 FASTFLOAT_TRY(shl_limbs(div));
566 }
567 return true;
568 }
569
570 // get the number of leading zeros in the bigint.
571 FASTFLOAT_CONSTEXPR20 int ctlz() const noexcept {
572 if (vec.is_empty()) {
573 return 0;
574 } else {
575 #ifdef FASTFLOAT_64BIT_LIMB
576 return leading_zeroes(vec.rindex(0));
577 #else
578 // no use defining a specialized leading_zeroes for a 32-bit type.
579 uint64_t r0 = vec.rindex(0);
580 return leading_zeroes(r0 << 32);
581 #endif
582 }
583 }
584
585 // get the number of bits in the bigint.
586 FASTFLOAT_CONSTEXPR20 int bit_length() const noexcept {
587 int lz = ctlz();
588 return int(limb_bits * vec.len()) - lz;
589 }
590
591 FASTFLOAT_CONSTEXPR20 bool mul(limb y) noexcept { return small_mul(vec, y); }
592
593 FASTFLOAT_CONSTEXPR20 bool add(limb y) noexcept { return small_add(vec, y); }
594
595 // multiply as if by 2 raised to a power.
596 FASTFLOAT_CONSTEXPR20 bool pow2(uint32_t exp) noexcept { return shl(exp); }
597
598 // multiply as if by 5 raised to a power.
599 FASTFLOAT_CONSTEXPR20 bool pow5(uint32_t exp) noexcept {
600 // multiply by a power of 5
601 size_t large_length = sizeof(large_power_of_5) / sizeof(limb);
602 limb_span large = limb_span(large_power_of_5, large_length);
603 while (exp >= large_step) {
604 FASTFLOAT_TRY(large_mul(vec, large));
605 exp -= large_step;
606 }
607 #ifdef FASTFLOAT_64BIT_LIMB
608 uint32_t small_step = 27;
609 limb max_native = 7450580596923828125UL;
610 #else
611 uint32_t small_step = 13;
612 limb max_native = 1220703125U;
613 #endif
614 while (exp >= small_step) {
615 FASTFLOAT_TRY(small_mul(vec, max_native));
616 exp -= small_step;
617 }
618 if (exp != 0) {
619 // Work around clang bug https://godbolt.org/z/zedh7rrhc
620 // This is similar to https://github.com/llvm/llvm-project/issues/47746,
621 // except the workaround described there don't work here
622 FASTFLOAT_TRY(small_mul(
623 vec, limb(((void)small_power_of_5[0], small_power_of_5[exp]))));
624 }
625
626 return true;
627 }
628
629 // multiply as if by 10 raised to a power.
630 FASTFLOAT_CONSTEXPR20 bool pow10(uint32_t exp) noexcept {
631 FASTFLOAT_TRY(pow5(exp));
632 return pow2(exp);
633 }
634 };
635
636 } // namespace fast_float
637
638 #endif