fixed_point128 1.0.1.0
128 bit integer, fixed point and floating point arithmetic for C++20
Loading...
Searching...
No Matches
int128_shared.h
Go to the documentation of this file.
1/***********************************************************************************
2 MIT License
3
4 Copyright (c) 2025 Eric Gur (ericgur@iname.com)
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23************************************************************************************/
24
25/***********************************************************************************
26 Acknologements
27
28************************************************************************************/
29
30/**
31 * @file int128_shared.h
32 * @brief Implementation shared by the 128 bit signed and unsigned integer types.
33 *
34 * Provides @ref fp128::int128_base, a single class template parameterized on the
35 * signedness of the type. @ref fp128::uint128_t and @ref fp128::int128_t are
36 * aliases of its two instantiations, declared by uint128_t.h and int128_t.h
37 * respectively. Include one of those headers rather than this one.
38 *
39 * @see uint128_t.h for the unsigned alias and its user-defined literal.
40 * @see int128_t.h for the signed alias, its user-defined literal and abs().
41 * @see fp128_shared.h for supporting intrinsics and utilities.
42 */
43
44#ifndef FP128_INT128_SHARED_H
45#define FP128_INT128_SHARED_H
46
47#include <format> // std::formatter
48#include <functional> // std::hash
49#include <limits>
50#include <istream>
51#include <ostream>
52#include "fp128_shared.h"
53
54namespace fp128
55{
56
57/***********************************************************************************
58 * Forward declarations
59 ************************************************************************************/
60class fp128_gtest; // Google test class
61
62/***********************************************************************************
63 * Main Code
64 ************************************************************************************/
65
66/**
67 * @brief 128 bit integer class, signed or unsigned depending on the template parameter.
68 *
69 * This class implements the standard operators a builtin integer type has.<BR>
70 * All of int128_base's methods are inline for maximum performance.<BR>
71 * Both instantiations store the same two QWORDs and only differ where the interpretation of
72 * the msb matters, which is why a single template covers them. The signed instantiation uses
73 * a two's complement representation, so addition, subtraction, multiplication, the bitwise
74 * operators, the left shift and equality are bit identical between the two and are written
75 * once, without a test on the signedness.
76 *
77 * <B>Implementation notes:</B>
78 * <UL>
79 * <LI>The signedness dependent code is selected with <TT>if constexpr (is_signed)</TT>, or by
80 * calling is_negative()/is_positive(), which are compile time constants for the unsigned
81 * instantiation and let the surrounding tests fold away.</LI>
82 * <LI>Overflow is handled silently, similar to builtin integer operations.</LI>
83 * <LI>An int128_base object is not thread safe. Accessing a const object from multiple threads is safe.</LI>
84 * <LI>int128_base is <B>conditionally safe</B>, 2 different non const objects can be accessed concurrently.</LI>
85 * <LI>Only 64 bit builds are supported.</LI>
86 * </UL>
87 *
88 * <B>Compile time evaluation:</B><BR>
89 * Everything that stays within integer arithmetic is constexpr:
90 * <UL>
91 * <LI>Construction from any builtin arithmetic type and from the two QWORDs, copy, move,
92 * assignment and the conversions to the integer and floating point types.</LI>
93 * <LI>Addition, subtraction, multiplication, square(), the increment and decrement operators,
94 * the shifts, the bitwise operators, the unary operators and the comparisons.</LI>
95 * <LI>The queries is_positive(), is_negative(), is_zero(), get_bit() and get_components(),
96 * and the constant one().</LI>
97 * <LI>The math functions abs, sqr, lzcnt128, log2 and pow.</LI>
98 * </UL>
99 *
100 * The bit counting and extended arithmetic intrinsics these rest on are not constant expressions,
101 * so fp128_shared.h wraps each one in a constexpr function that serves a constant
102 * evaluated call from a portable implementation of the same operation. A runtime call still
103 * reaches the bare intrinsic and generates the same code it did before.
104 *
105 * The rest cannot be constexpr, for one of two reasons:
106 * <UL>
107 * <LI>Division and modulo, and sqrt which is built on them. The paths for a divisor that fits in
108 * 64 bit rest on the _udiv128 intrinsic, and one of them writes both QWORDs through a pointer
109 * to the first, which is out of bounds as far as constant evaluation is concerned. A 128 bit
110 * divisor goes through div_128bit, which has no such obstacle of its own.</LI>
111 * <LI>The string conversions allocate, and log/log10 look their result up in a function local
112 * static table, which a constexpr function may not declare.</LI>
113 * </UL>
114 *
115 * @tparam IsSigned True for a two's complement signed type, false for an unsigned one.
116 */
117template <bool IsSigned> class FP128_ALIGN16 int128_base
118{
119 // build time validation of template parameters
120 static_assert(sizeof(void*) == 8, "int128_base is supported in 64 bit builds only!");
121 friend class fp128_gtest;
122
123private:
124 //
125 // members
126 //
127 uint64_t low; ///< Lower 64 bits (QWORD).
128 uint64_t high; ///< Upper 64 bits (QWORD). For the signed type the sign is in the MSB (two's complement).
129
130 /**
131 * @brief Produces the upper QWORD when sign extending a builtin integral value.
132 * The test is compiled out for unsigned types, which also keeps the compiler from warning
133 * about an unsigned or bool value being compared against zero.
134 * @tparam T Any builtin integral type
135 * @param x Input value
136 * @return All ones when x is negative, zero otherwise.
137 */
138 template <typename T> [[nodiscard]] static constexpr uint64_t HighFromIntegral(T x) noexcept
139 {
140 if constexpr (std::is_signed_v<T>) {
141 return (x < T(0)) ? UINT64_MAX : 0;
142 } else {
143 return 0;
144 }
145 }
146 /**
147 * @brief Compares the magnitude of this object with another, treating both as unsigned.
148 *
149 * The division code converts its operands to absolute values and from that point on they are
150 * magnitudes, not signed numbers. The signed comparison operators would misread the magnitude
151 * of the most negative value, whose absolute value keeps the sign bit set.
152 *
153 * @param rhs Right hand side operand
154 * @return True when this object's bit pattern is larger when read as an unsigned integer.
155 */
156 [[nodiscard]] FP128_FORCE_INLINE constexpr bool MagnitudeGreaterThan(const int128_base& rhs) const noexcept
157 {
158 return high > rhs.high || (high == rhs.high && low > rhs.low);
159 }
160 /**
161 * @brief Extracts the mantissa of a floating point representation of this object, rounded.
162 *
163 * Keeps the frac_bits+1 most significant bits and rounds the dropped remainder to nearest,
164 * ties going to even. This is what IEEE 754 mandates and what the builtin integer to floating
165 * point conversions do, so the result matches converting via a wider builtin type.<BR>
166 * Rounding needs three pieces of information: the bits that survive, the highest dropped bit
167 * (which chooses the direction) and whether anything below it is set (the sticky bit, which
168 * distinguishes an exact tie from a remainder larger than half).<BR>
169 * Expects this object to hold a magnitude (the conversion operators take the absolute value
170 * before calling it), so the sign bit plays no part.
171 *
172 * @param expo Bit position of the msb of this object. Must be larger than frac_bits.
173 * @param frac_bits Fraction bit count of the target type, 23 for float or 52 for double.
174 * @return The rounded mantissa. Holds frac_bits+1 bits, or frac_bits+2 when rounding carried
175 * into the next power of 2.
176 */
177 [[nodiscard]] FP128_INLINE constexpr uint64_t RoundedMantissa(uint64_t expo, int32_t frac_bits) const noexcept
178 {
179 const int32_t shift = static_cast<int32_t>(expo) - frac_bits; // count of dropped bits, at least 1
180 uint64_t mant = shift_right128(low, high, shift);
181
182 // the highest dropped bit sits just below the mantissa
183 const uint64_t round_bit = (shift <= 64) ? FP128_GET_BIT(low, shift - 1) : FP128_GET_BIT(high, shift - 65);
184 if (round_bit == 0)
185 return mant; // remainder is below half, round down
186
187 // is anything set below the rounding bit? Each branch below shifts the bits of interest
188 // to the top of the QWORD, which avoids building a mask of a variable width.
189 bool sticky;
190 if (shift < 2) {
191 sticky = false; // the rounding bit is the only dropped bit
192 } else if (shift <= 64) {
193 sticky = (low << (65 - shift)) != 0; // bits [shift-2:0] of low
194 } else if (shift == 65) {
195 sticky = low != 0; // all of low, nothing of high
196 } else {
197 sticky = low != 0 || (high << (129 - shift)) != 0; // all of low plus bits [shift-66:0] of high
198 }
199
200 // above half always rounds up, an exact tie rounds towards the even mantissa
201 if (sticky || (mant & 1))
202 ++mant;
203
204 return mant;
205 }
206 /**
207 * @brief Compares this object with a floating point value exactly, as real numbers.
208 *
209 * Converting the value to int128_base and comparing the two would truncate a fraction away
210 * (2 == 2.5 would hold) and saturate NaN, the infinities and anything else out of range (the
211 * largest value would equal all three). This compares against the value itself instead.<BR>
212 * Out of range values order beyond every value of the type. A value in range truncates
213 * towards zero to an integer t exactly, and t converts back to a double exactly as well, since
214 * truncating cannot add significant bits. No integer lies strictly between the value and t, so
215 * comparing this object with t settles the order whenever the two differ; when they are equal,
216 * the discarded fraction decides it.<BR>
217 * A long double wider than double is compared through double, as the constructor converts it.
218 *
219 * @param x Value to compare with.
220 * @return -1, 0 or 1 when this object is smaller than, equal to or larger than x, and 2 when x
221 * is a NaN, with which nothing is ordered.
222 */
223 template <typename F> [[nodiscard]] FP128_INLINE constexpr int32_t CompareFloating(F x) const noexcept
224 {
225 const double d = static_cast<double>(x);
226 if (d != d) {
227 return 2;
228 }
229
230 // 2^64 * 2^64 is 2^128, and every factor here is exact in a double
231 constexpr double two_64 = 18446744073709551616.0;
232 if constexpr (is_signed) {
233 constexpr double two_127 = two_64 * 9223372036854775808.0;
234 if (d >= two_127)
235 return -1;
236 if (d < -two_127)
237 return 1;
238 } else {
239 if (d >= two_64 * two_64)
240 return -1;
241 // every unsigned value lies above a negative one, and -0.0 is not negative here
242 if (d < 0)
243 return 1;
244 }
245
246 const int128_base t(d);
247 if (*this != t) {
248 return (*this < t) ? -1 : 1;
249 }
250
251 const double td = static_cast<double>(t);
252 if (d == td)
253 return 0;
254
255 return (d > td) ? -1 : 1;
256 }
257
258public:
259 static constexpr bool is_signed = IsSigned; ///< True when the msb of the high QWORD is a sign bit.
260
261 typedef int128_base type; ///< Self type alias.
262 typedef int128_base* ptr_type; ///< Pointer type alias.
263 typedef int128_base& ref_type; ///< Reference type alias.
264
265 //
266 // Constructors
267 //
268
269 /**
270 * @brief Default constructor, creates an instance with a value of zero.
271 * Explicitly zeroing both QWORDs rather than defaulting the constructor keeps the type usable
272 * in a constant expression, which a default initialized object with indeterminate members is not.
273 */
274 FP128_FORCE_INLINE constexpr int128_base() noexcept : low(0), high(0) {}
275 /**
276 * @brief Copy constructor
277 *
278 * Copies the two QWORDs individually instead of being defaulted. The difference is not
279 * stylistic: a defaulted copy is trivial, and MSVC implements a trivial 16 byte copy with a
280 * single `vmovups` once `/arch:AVX2` is on. Every operator here produces its result as two
281 * QWORD stores into a stack temporary, so that one wide load overlaps both of them, fails
282 * store to load forwarding, and stalls for roughly 15 cycles waiting for them to reach L1.
283 * It lands on any expression whose 128 bit result goes to memory - `*out = *a * *b` is enough.
284 *
285 * Spelling the copy out member by member keeps every store and load 8 bytes wide, which
286 * forwards. Measured on MSVC over 64K element arrays, interleaving the two builds so that
287 * drift hits both equally: 1.7x on sqrt(), 1.4x on division by a 128 bit value, 1.05x on
288 * addition, and no measurable change to multiplication, log10(), pow() or division by a
289 * 64 bit integer. Nothing measured slower.
290 *
291 * The type stops being trivially copyable, so `std::bit_cast` no longer accepts it and a
292 * container of these relocates with a copy loop rather than a `memmove` - which at this size
293 * is not a loss either: growing a std::vector of them measured 1.35x faster.
294 * `fixed_point128` and `float128` have always been written this way, for the same reason.
295 *
296 * @param rhs Object to copy from.
297 */
298 FP128_FORCE_INLINE constexpr int128_base(const int128_base& rhs) noexcept : low(rhs.low), high(rhs.high) {}
299 /**
300 * @brief Move constructor
301 * Doesn't modify the right hand side object. Acts like a copy constructor.
302 * @param rhs Object to copy from.
303 */
304 FP128_FORCE_INLINE constexpr int128_base(int128_base&& rhs) noexcept : low(rhs.low), high(rhs.high) {}
305 /**
306 * @brief Constructor from the double type
307 * Underflow goes to zero. Overflow, NaN and +-INF go to the largest supported magnitude of
308 * the matching sign.<BR>
309 * For the unsigned type a negative value wraps around via 2's complement, matching both the
310 * integer constructors and the way builtin unsigned types behave. For example -5.0 yields
311 * 2^128 - 5.
312 * @param x Input value
313 */
314 constexpr int128_base(double x) noexcept
315 {
316 const Double d(x);
317 // very common case
318 if (x == 0) {
319 low = high = 0;
320 return;
321 }
322
323 const int32_t e = static_cast<int32_t>(d.e()) - 1023;
324 uint64_t f = d.f();
325
326 // overflow which catches NaN and Inf
327 if constexpr (is_signed) {
328 // -(2**127) is represented correctly (doesn't overflow)
329 if (e > 126) {
330 if (d.s() == 0) {
331 high = 0x8000000000000000ull - 1;
332 low = UINT64_MAX;
333 } else {
334 high = 0x8000000000000000ull;
335 low = 0;
336 }
337 return;
338 }
339 } else {
340 if (e > 127) {
341 high = low = UINT64_MAX;
342 return;
343 }
344 }
345
346 // normal number, produces non zero value
347 if (e >= 0) {
348 // bit 52 in f is the unity value of the float. it needs to move to the unity position in fixed point
350 const int32_t bits_to_shift = e - dbl_frac_bits;
351 low = f;
352 high = 0;
353
354 // f fits in high QWORD
355 if (bits_to_shift > 0) {
356 *this <<= bits_to_shift;
357 }
358 // shift right
359 else {
360 *this >>= -bits_to_shift;
361 }
362
363 // negative number, the unsigned type wraps around just like the integer constructors do
364 if (d.s()) {
365 twos_complement128(low, high);
366 }
367 }
368 // too small to be represented, no need to bother.
369 else {
370 high = low = 0;
371 }
372 }
373 /**
374 * @brief Constructor from any builtin integral type.
375 *
376 * A single constrained template is used instead of one overload per fixed width type.
377 * Overloads would only cover the types the fixed width aliases happen to name on a given
378 * platform, leaving the rest ambiguous: on MSVC, long and unsigned long are distinct from
379 * both int and long long, so int128_base(1ul) could not pick a best match. Which of long and
380 * long long int64_t names also differs between LP64 and LLP64, so no fixed set of overloads
381 * covers every platform.<BR>
382 * Signed values are sign extended, unsigned values are zero extended. For the unsigned type a
383 * negative value therefore wraps around via 2's complement, exactly like the builtin unsigned
384 * types do.
385 * @tparam T Any builtin integral type (including bool and the character types)
386 * @param x Input value
387 */
388 template <typename T>
389 requires std::is_integral_v<T>
390 FP128_FORCE_INLINE constexpr int128_base(T x) noexcept : low(static_cast<uint64_t>(x)), high(HighFromIntegral(x))
391 {
392 }
393 /**
394 * @brief Constructor from const char* (C string).
395 * Allows creating 128 bit values from a string. Much slower than the other constructors.<BR>
396 * Input string can be decimal or hex. Hex initialization is faster. Commas and apostrophes are
397 * ignored, so both conventional digit grouping and the C++ digit separator are accepted, the
398 * latter being what reaches the type's user defined literals. A nullptr, an empty string or a
399 * leading illegal character all
400 * produce zero; parsing otherwise stops at the first character that isn't a digit of the
401 * detected base. Overflow wraps around silently, like the builtin integer types.<BR>
402 * An optional leading '+' or '-' is accepted. For the unsigned type a negative value wraps
403 * around via 2's complement, so "-5" and -5.0 both produce 2^128 - 5, matching strtoull.<BR>
404 * Never throws: an allocation failure produces zero.
405 * @param x Input string
406 */
407 int128_base(const char* x) noexcept
408 {
409 low = high = 0;
410
411 if (x == nullptr)
412 return;
413
414 const auto x_len = 1 + strlen(x);
415 // make_unique_for_overwrite throws bad_alloc, which this noexcept constructor must not
416 // propagate. The nothrow form reports a failed allocation as a null pointer instead.
417 auto str_ptr = std::unique_ptr<char[]>(new (std::nothrow) char[x_len]);
418 char* p = str_ptr.get();
419 if (p == nullptr)
420 return;
421
422 strnlwr(p, x, x_len);
423
424 // trim leading white space. The cast keeps a negative char from reaching isspace, which
425 // only accepts values representable as unsigned char (or EOF).
426 while (*p && isspace(static_cast<unsigned char>(*p)))
427 ++p;
428
429 // An optional sign, which has to be consumed before the base prefix so that "-0x10" is
430 // recognized as hex. The magnitude is parsed first and negated at the end.
431 bool negative = false;
432 if (*p == '-' || *p == '+') {
433 negative = (*p == '-');
434 ++p;
435 }
436
437 // base 10 or 16 are supported
438 const uint32_t base = (0 == strncmp("0x", p, 2)) ? 16u : 10u;
439 if (base == 16)
440 p += 2;
441
442 // trim leading zeros
443 while (*p == '0')
444 ++p;
445
446 // convert one digit at a time
447 while (*p && !isspace(static_cast<unsigned char>(*p)) && *p != '.') {
448 uint64_t d = static_cast<unsigned char>(*p);
449 if (d >= '0' && d <= '9')
450 d -= '0';
451 else if (base == 16 && (d >= 'a' && d <= 'f'))
452 d = 10ull + d - 'a';
453 // Digit grouping separators are skipped. The apostrophe matters for the user defined
454 // literals: a raw literal operator receives the source characters of its token and the
455 // compiler does not strip the C++ digit separator out of them, so 1'000'000_uint128
456 // arrives here as "1'000'000" and would otherwise stop parsing at the first separator,
457 // silently yielding 1.
458 else if (d == ',' || d == '\'') {
459 ++p;
460 continue;
461 } else
462 break; // treat an unknown char as end of string
463
464 // 4 bits per digit
465 if (base == 16) {
466 *this <<= 4;
467 low |= d;
468 } else {
469 *this *= base;
470 *this += d;
471 }
472
473 ++p;
474 }
475
476 // negate the magnitude. For the unsigned type this wraps around, the same way the numeric
477 // constructors and strtoull do.
478 if (negative) {
479 twos_complement128(low, high);
480 }
481 }
482 /**
483 * @brief Constructor from std::string.
484 * Allows creating very high precision values. Much slower than the other constructors.
485 * @param x Input string
486 */
487 int128_base(const std::string& x) noexcept { *this = x.c_str(); }
488 /**
489 * @brief Constructor from the 2 int128_base elements, useful for creating special constants.
490 * @param l Low QWORD
491 * @param h High QWORD
492 */
493 FP128_FORCE_INLINE constexpr int128_base(uint64_t l, uint64_t h) noexcept : low(l), high(h) {}
494 /**
495 * @brief Destructor
496 */
497 constexpr ~int128_base() noexcept = default;
498 /**
499 * @brief Assignment operator
500 * Assigns the two QWORDs individually rather than being defaulted; see the copy constructor
501 * for why the width of the copy matters.
502 * @param rhs Value to copy from
503 * @return This object.
504 */
505 FP128_FORCE_INLINE constexpr int128_base& operator=(const int128_base& rhs) noexcept
506 {
507 low = rhs.low;
508 high = rhs.high;
509 return *this;
510 }
511 /**
512 * @brief Move assignment operator
513 * Doesn't modify the right hand side object. Acts like a copy assignment operator.
514 * @param rhs Value to copy from
515 * @return This object.
516 */
518 {
519 low = rhs.low;
520 high = rhs.high;
521 return *this;
522 }
523 /**
524 * @brief Assignment operator
525 * @param rhs Value to copy from
526 * @return This object.
527 */
528 template <typename T> FP128_FORCE_INLINE constexpr int128_base& operator=(const T& rhs) noexcept
529 {
530 *this = int128_base(rhs);
531 return *this;
532 }
533
534 //
535 // conversion operators
536 //
537 /**
538 * @brief operator uint64_t - converts to a uint64_t
539 * @return Object value.
540 */
541 [[nodiscard]] FP128_FORCE_INLINE constexpr operator uint64_t() const noexcept { return low; }
542 /**
543 * @brief operator int64_t - converts to a int64_t
544 * @return Object value.
545 */
546 [[nodiscard]] FP128_FORCE_INLINE constexpr operator int64_t() const noexcept { return static_cast<int64_t>(low); }
547 /**
548 * @brief operator uint32_t - converts to a uint32_t
549 * @return Object value.
550 */
551 [[nodiscard]] FP128_FORCE_INLINE constexpr operator uint32_t() const noexcept { return static_cast<uint32_t>(low); }
552 /**
553 * @brief operator int32_t - converts to a int32_t
554 * @return Object value.
555 */
556 [[nodiscard]] FP128_FORCE_INLINE constexpr operator int32_t() const noexcept { return static_cast<int32_t>(low); }
557 /**
558 * @brief operator float - converts to a float
559 * The signed range fits within a float's exponent, so no signed value overflows. Unsigned
560 * values above FLT_MAX become infinity, as they do with the builtin unsigned conversions:
561 * the carry out of the rounding step below pushes the exponent to its all ones encoding.
562 * @return Object value, rounded to nearest with ties going to even.
563 */
564 [[nodiscard]] FP128_INLINE constexpr operator float() const noexcept
565 {
566 if (is_zero())
567 return 0;
568
569 // the magnitude is what gets converted, the sign is carried in the result's sign bit.
570 // Both tests are a compile time false for the unsigned instantiation.
571 int128_base temp = *this;
572 const bool sign = is_negative();
573 if (sign) {
574 twos_complement128(temp.low, temp.high);
575 }
576
577 // log2 of the magnitude. The free function form is used because the absolute value of the
578 // most negative value keeps its sign bit set, which the int128_base overload rejects.
579 const uint64_t expo = log2(temp.low, temp.high); // returns the bit location of the msb
580 // the value fits in the fraction, no bits are lost so no rounding is needed.
581 // float doesn't hold the msb, it's implicit, so bit [22:0] hold the rest of the value
582 if (expo <= flt_frac_bits) {
583 return Float::make(sign, static_cast<uint32_t>(expo) + 127, static_cast<uint32_t>(temp.low << (flt_frac_bits - expo)));
584 }
585
586 // more bits than the fraction can hold, drop the extra ones with rounding.
587 // rounding up can carry into the next power of 2, costing a fraction bit and
588 // incrementing the exponent. An exponent of 255 is the encoding of infinity, which is
589 // exactly what an unsigned value above FLT_MAX must produce.
590 const uint64_t mant = temp.RoundedMantissa(expo, flt_frac_bits);
591 const uint64_t carry = mant >> (flt_frac_bits + 1);
592 return Float::make(sign, static_cast<uint32_t>(expo + carry) + 127, static_cast<uint32_t>(mant >> carry));
593 }
594 /**
595 * @brief operator double - converts to a double
596 * The whole 128 bit range is within reach of a double's exponent, so no value overflows.
597 * @return Object value, rounded to nearest with ties going to even.
598 */
599 [[nodiscard]] FP128_INLINE constexpr operator double() const noexcept
600 {
601 if (is_zero())
602 return 0;
603
604 // the magnitude is what gets converted, the sign is carried in the result's sign bit.
605 // Both tests are a compile time false for the unsigned instantiation.
606 int128_base temp = *this;
607 const bool sign = is_negative();
608 if (sign) {
609 twos_complement128(temp.low, temp.high);
610 }
611
612 // log2 of the magnitude. The free function form is used because the absolute value of the
613 // most negative value keeps its sign bit set, which the int128_base overload rejects.
614 // It is also noexcept, which the overload that throws on a zero input is not.
615 const uint64_t expo = log2(temp.low, temp.high); // returns the bit location of the msb
616 // the value fits in the fraction, no bits are lost so no rounding is needed.
617 // double doesn't hold the msb, it's implicit, so bit [51:0] hold the rest of the value
618 if (expo <= dbl_frac_bits) {
619 return Double::make(sign, expo + 1023, temp.low << (dbl_frac_bits - expo));
620 }
621
622 // more bits than the fraction can hold, drop the extra ones with rounding.
623 // rounding up can carry into the next power of 2, costing a fraction bit and
624 // incrementing the exponent
625 const uint64_t mant = temp.RoundedMantissa(expo, dbl_frac_bits);
626 const uint64_t carry = mant >> (dbl_frac_bits + 1);
627 return Double::make(sign, expo + carry + 1023, mant >> carry);
628 }
629 /**
630 * @brief operator long double - converts to a long double
631 * @return Object value.
632 */
633 [[nodiscard]] FP128_FORCE_INLINE constexpr operator long double() const noexcept { return operator double(); }
634 /**
635 * @brief Converts to a char* (slow) string holds all meaningful fraction bits.
636 * @return object string representation
637 */
638 [[nodiscard]] FP128_FORCE_INLINE char* to_string() const noexcept { return operator char*(); }
639 /**
640 * @brief Converts to a std::string (slow) string holds all meaningful fraction bits.
641 * @return object string representation
642 */
643 [[nodiscard]] FP128_INLINE operator std::string() const { return operator char*(); }
644 /**
645 * @brief Converts to a C string (slow) string holds all meaningful fraction bits.
646 * The returned string is a statically, thread-allocated buffer.
647 * Additional calls to this function from the same thread, overwrite the previous result.
648 * @return C string with describing the value of the object.
649 * @return object string representation
650 */
651 [[nodiscard]] explicit FP128_INLINE operator char*() const noexcept
652 {
653 constexpr int buff_size = 45;
654 static thread_local char str[buff_size];
655
656 // Small numbers, use the fast snprintf method.
657 if constexpr (is_signed) {
658 // The value round trips through an int64_t only when the high QWORD is nothing but
659 // copies of the sign bit of the low QWORD. Testing high == 0 alone would hand %lld a
660 // negative number for every value in [2^63, 2^64), printing 2^64-1 as "-1". It also
661 // lets small negatives take this path, whose high QWORD is all ones.
662 if (high == static_cast<uint64_t>(static_cast<int64_t>(low) >> 63)) {
663 snprintf(str, buff_size, "%lld", static_cast<int64_t>(low));
664 return str;
665 }
666 } else {
667 if (high == 0) {
668 snprintf(str, buff_size, "%llu", low);
669 return str;
670 }
671 }
672
673 // the digits are produced from the magnitude, both tests below are a compile time false
674 // for the unsigned instantiation
675 int128_base temp = *this;
676 const bool sign = is_negative();
677 if (sign) {
678 twos_complement128(temp.low, temp.high);
679 }
680
681 // The digits are written backwards starting at the terminator, which sits at the very end
682 // of the buffer. The longest result is 39 digits plus a sign, well within the 44 available.
683 str[buff_size - 1] = 0;
684 char* p = str + buff_size - 1; // writing the string in reverse
685 uint64_t q[2] {};
686 uint64_t digit {};
687 // as long as the intermediate value is >64 bit, use the more expensive long division.
688 while (temp.high) {
689 const uint64_t nom[2] = {temp.low, temp.high};
690 div_64bit((uint64_t*)q, &digit, (uint64_t*)nom, 10ull, 2);
691 temp.low = q[0];
692 temp.high = q[1];
693 *--p = static_cast<char>(digit + '0');
694 }
695 // the intermediate value fits in 64 bit, use the much faster native-64 bit division
696 while (temp.low) {
697 uint64_t r = temp.low % 10ull;
698 temp.low /= 10ull;
699 *--p = static_cast<char>(r + '0');
700 }
701
702 if (sign) {
703 *--p = '-';
704 }
705
706 return p;
707 }
708
709 //
710 // math operators
711 //
712
713 /**
714 * @brief Performs right shift operation.
715 * @param shift bits to shift
716 * @return Temporary object with the result of the operation
717 */
718 [[nodiscard]] FP128_FORCE_INLINE constexpr int128_base operator>>(int32_t shift) const noexcept
719 {
720 int128_base temp(*this);
721 return temp >>= shift;
722 }
723 /**
724 * @brief Performs left shift operation.
725 * @param shift bits to shift
726 * @return Temporary object with the result of the operation
727 */
728 [[nodiscard]] FP128_FORCE_INLINE constexpr int128_base operator<<(int32_t shift) const noexcept
729 {
730 int128_base temp(*this);
731 return temp <<= shift;
732 }
733 /**
734 * @brief Add a value to this object
735 * like other builtin integer types, overflow wraps around silently
736 * @param rhs Right hand side operand
737 * @return This object.
738 */
739 FP128_FORCE_INLINE constexpr int128_base& operator+=(const int128_base& rhs) noexcept
740 {
741 const uint8_t carry = addcarryx_u64(0, low, rhs.low, &low);
742 addcarryx_u64(carry, high, rhs.high, &high);
743 return *this;
744 }
745 /**
746 * @brief Add a value to this object
747 * like other builtin integer types, overflow wraps around silently
748 * @param rhs Right hand side operand
749 * @return This object.
750 */
751 template <typename T> FP128_FORCE_INLINE constexpr int128_base& operator+=(const T& rhs) noexcept { return operator+=(int128_base(rhs)); }
752 /**
753 * @brief Subtract a value from this object
754 * like other builtin integer types, underflow wraps around silently
755 * @param rhs Right hand side operand
756 * @return This object.
757 */
758 FP128_FORCE_INLINE constexpr int128_base& operator-=(const int128_base& rhs) noexcept
759 {
760 // Subtracting directly rather than adding the two's complement of rhs. Both are the same
761 // difference modulo 2^128, but neither compiler folds the negate-and-add form back into a
762 // borrow chain: MSVC emits the whole neg/not/sete sequence and lands on twice the
763 // instruction count of operator+=. Writing the difference back in place is safe when rhs
764 // aliases this object, each QWORD of rhs being read before its counterpart is overwritten.
765 const uint8_t borrow = subborrow_u64(0, low, rhs.low, &low);
766 subborrow_u64(borrow, high, rhs.high, &high);
767 return *this;
768 }
769 /**
770 * @brief Subtract a value from this object
771 * like other builtin integer types, underflow wraps around silently
772 * @param rhs Right hand side operand
773 * @return This object.
774 */
775 template <typename T> FP128_FORCE_INLINE constexpr int128_base& operator-=(const T& rhs) noexcept { return operator-=(int128_base(rhs)); }
776 /**
777 * @brief Multiplies a value to this object
778 *
779 * The same code serves both instantiations. A truncated 128 bit product is a multiplication
780 * modulo 2^128, and in that ring the two's complement bit pattern of a negative value is its
781 * value, so multiplying the raw bits gives the signed result without converting the operands
782 * to magnitudes and reapplying the sign. int128_base::square() relies on the same identity.
783 *
784 * @param rhs Right hand side operand
785 * @return This object.
786 */
787 FP128_FORCE_INLINE constexpr int128_base& operator*=(const int128_base& rhs) noexcept
788 {
789 // Snapshot both operands before writing anything. The multiply below overwrites both
790 // QWORDs of this object, and rhs is allowed to alias it (e.g. a *= a), so reading
791 // rhs after that point would pick up the partial result instead of the operand.
792 const uint64_t l = low, h = high;
793 const uint64_t rhs_l = rhs.low, rhs_h = rhs.high;
794
795 // multiply low QWORDs
796 low = mulx_u64(l, rhs_l, &high);
797
798 // multiply low this and high rhs; multiply high this and low rhs
799 high += l * rhs_h + h * rhs_l;
800 return *this;
801 }
802 /**
803 * @brief Squares this object in place.
804 *
805 * Cheaper than `operator*=(*this)`: a square is symmetric, so the `low*high` and `high*low`
806 * cross products are the same value. Computing it once and doubling it replaces one of
807 * the three multiplies with an addition. The temporary copy that `operator*=` needs to
808 * guard against aliasing is not needed either.
809 *
810 * The result is truncated to 128 bit and is bit identical to `(*this) * (*this)`, which for
811 * the signed type means it is negative in the same overflow cases.
812 *
813 * @return This object.
814 */
816 {
817 const uint64_t l = low, h = high;
818
819 // multiply the low QWORD by itself
820 low = mulx_u64(l, l, &high);
821
822 // the low * high cross product appears twice in the sum, so double it.
823 // Both operands only contribute their lower 64 bit to the result.
824 high += 2 * (l * h);
825 return *this;
826 }
827 /**
828 * @brief Multiplies a value to this object
829 *
830 * A non negative operand that fits in 64 bit skips one of the three partial products. It is
831 * valid for both instantiations for the same reason operator*=(const int128_base&) is: the
832 * product is taken modulo 2^128, where the two's complement bits of this object are its value.
833 *
834 * Restricted to the arithmetic types. Any other operand used to reach the static_cast to
835 * uint64_t below through a conversion operator and was silently truncated: the other
836 * instantiation (`int128_t(3) * uint128_t(2^64 + 1)` gave 3) and float128 among them. Such an
837 * operand now has to convert to int128_base implicitly or the expression does not compile, as
838 * is already the case for the other mixed arithmetic operators.
839 *
840 * @param x Right hand side operand
841 * @return This object.
842 */
843 template <typename T>
844 requires std::is_arithmetic_v<T>
846 {
847 // floating point values are converted first. Casting them straight to uint64_t below
848 // would be undefined behavior for anything at or above 2^64 and would silently drop the
849 // upper bits of operands the int128_base constructor handles exactly.
850 if constexpr (std::is_floating_point_v<T>) {
851 return operator*=(int128_base(x));
852 }
853 // check if the type is signed or not
854 // for negative values, convert to int128_base and multiply.
855 else if constexpr (std::is_signed_v<T>) {
856 if (x < 0)
857 return operator*=(int128_base(x));
858 }
859
860 uint64_t temp;
861 const uint64_t uval = static_cast<uint64_t>(x);
862 // multiply low QWORDs
863 low = mulx_u64(low, uval, &temp);
864 high = high * uval + temp;
865
866 return *this;
867 }
868 /**
869 * @brief Divide this object by rhs.
870 *
871 * Rounds towards zero, matching the builtin integer types: -7 / 2 is -3, not -4. The two
872 * operands are reduced to magnitudes, divided as unsigned values (which truncates), and the
873 * sign is applied afterwards, which is exactly truncation towards zero. Every sign related
874 * step below folds away for the unsigned instantiation.
875 *
876 * @param rhs_in Right hand side operator (denominator)
877 * @return this object.
878 */
880 {
881 // The signed path negates a negative divisor before dividing, so it needs its own copy.
882 // The copy also makes a divisor that aliases this object (a /= a) safe.
883 int128_base rhs = rhs_in;
884
885 // check some trivial cases
886 if (rhs.is_zero()) {
888 }
889 if (is_zero()) {
890 low = high = 0;
891 return *this;
892 }
893 if (rhs == *this) {
894 low = 1;
895 high = 0;
896 return *this;
897 }
898
899 // convert both to absolute values. From here on the two are magnitudes, so every
900 // comparison and shift below has to treat them as unsigned.
901 const bool sign = is_negative();
902 const bool rhs_sign = rhs.is_negative();
903 const bool res_is_negative = sign != rhs_sign;
904 if (sign) {
905 twos_complement128(low, high);
906 }
907 if (rhs_sign) {
908 twos_complement128(rhs.low, rhs.high);
909 }
910
911 // a smaller magnitude divided by a larger one truncates to zero, whatever the signs
912 if (rhs.MagnitudeGreaterThan(*this)) {
913 low = high = 0;
914 return *this;
915 }
916
917 // exponent of 2, convert to a much faster shift operation
918 if (1 == popcnt128(rhs.low, rhs.high)) {
919 // the free function form of log2 is used because the magnitude of the most negative
920 // value keeps its sign bit set, which the int128_base overload rejects
921 const auto bits = static_cast<int32_t>(log2(rhs.low, rhs.high));
922 // operator>>= would replicate the sign bit, this is a magnitude and needs a logical
923 // shift. A shift of zero (dividing by 1) would also be undefined below.
924 if (bits > 0) {
925 low = shift_right128(low, high, bits);
926 high = (bits < 64) ? (high >> bits) : 0;
927 }
928 } else {
929 uint64_t q[2] {};
930 const uint64_t nom[2] = {low, high};
931
932 // optimization for when dividing by a small (<= 64 bit) integer
933 if (rhs.high == 0) {
934 if (!div_64bit((uint64_t*)q, nullptr, (uint64_t*)nom, rhs.low, 2)) {
936 }
937 }
938 // divide by a 128 bit divisor. The quotient of two 128 bit values with a divisor this
939 // large fits in a single QWORD, so div_128bit fills q[0] and leaves q[1] at zero.
940 else {
941 const uint64_t denom[2] = {rhs.low, rhs.high};
942 if (!div_128bit<array_length(nom)>(q, nullptr, nom, denom)) {
944 }
945 }
946 low = q[0];
947 high = q[1];
948 }
949
950 // apply sign if needed
951 if (res_is_negative) {
952 twos_complement128(low, high);
953 }
954
955 return *this;
956 }
957 /**
958 * @brief Divide this object by x.
959 *
960 * The unsigned type keeps a dedicated path for a divisor that fits in 64 bit, which writes the
961 * quotient straight into this object. The signed type delegates to the int128_base overload
962 * instead: the shortcut for a small numerator relies on an unsigned comparison, which would
963 * zero every negative value, and the overload it defers to already special cases a divisor
964 * that fits in 64 bit.
965 *
966 * @param x Right hand side operator (denominator)
967 * @return this object.
968 */
969 template <typename T> FP128_FORCE_INLINE int128_base& operator/=(T x)
970 {
971 if constexpr (is_signed) {
972 return operator/=(int128_base(x));
973 } else {
974 if (x == 0) {
976 }
977
978 // floating point values are converted first, which truncates them towards zero the way
979 // the constructor does. Casting them straight to uint64_t below would be undefined
980 // behavior for anything at or above 2^64. A divisor whose magnitude is below one
981 // therefore converts to zero and raises the divide by zero exception, as dividing by
982 // the converted value would.
983 if constexpr (std::is_floating_point_v<T>) {
984 return operator/=(int128_base(x));
985 }
986 // check if the type is signed or not
987 // for negative values only, convert to int128_base and divide.
988 else if constexpr (std::is_signed_v<T>) {
989 if (x < 0)
990 return operator/=(int128_base(x));
991 }
992
993 uint64_t uval = static_cast<uint64_t>(x);
994
995 // check some trivial cases
996 if (is_zero() || *this < uval) {
997 low = high = 0;
998 return *this;
999 }
1000
1001 if (*this == uval) {
1002 low = 1;
1003 high = 0;
1004 return *this;
1005 }
1006
1007 // exponent of 2, convert to a much faster shift operation
1008 if (1 == popcnt64(uval)) {
1009 return *this >>= (int32_t)log2(uval);
1010 }
1011
1012 // Numerator and quotient are both the members themselves, which are adjacent QWORDs in
1013 // a standard layout class. div_64bit() reads u[j] into a local before it writes q[j] and
1014 // never looks at u[j] again, and it walks j downwards, so letting the two alias is safe.
1015 //
1016 // Neither array is a copy for a reason. A `{low, high}` numerator, or a local quotient
1017 // copied back over the members, is a 16 byte load to MSVC, and it overlaps the QWORD
1018 // stores on the other side of it without being able to forward from them. One such copy
1019 // in front of the two divisions and one behind them cost 3.2x on `out[i] = in[i] / 5`.
1020 //
1021 // Every early return in div_64bit() that leaves the quotient unwritten is unreachable
1022 // from here: a numerator below or equal to the divisor is what the two trivial cases
1023 // above already returned for, and a zero numerator is the `is_zero()` check.
1024 if (!div_64bit(&low, nullptr, &low, uval, 2)) {
1026 }
1027 return *this;
1028 }
1029 }
1030 /**
1031 * @brief %= operator
1032 *
1033 * For the signed type the remainder takes the sign of the dividend, matching the builtin
1034 * integer types: -7 % 2 is -1. It is derived from the quotient so the two can never disagree.
1035 * The unsigned type gets the remainder straight out of the division instead, which is cheaper.
1036 *
1037 * @param rhs Modulo operand.
1038 * @return This object.
1039 */
1041 {
1042 if (rhs.is_zero()) {
1044 }
1045
1046 if constexpr (is_signed) {
1047 // x mod y == x - y * trunc(x / y), which keeps the identity (x/y)*y + x%y == x
1048 const int128_base quotient = *this / rhs;
1049 *this -= rhs * quotient;
1050 return *this;
1051 } else {
1052 // check some trivial cases
1053 if (*this < rhs)
1054 return *this;
1055
1056 if (*this == rhs) {
1057 low = 0;
1058 high = 0;
1059 return *this;
1060 }
1061
1062 uint64_t q[2] {};
1063 const uint64_t nom[2] = {low, high};
1064
1065 // optimization for when dividing by a small integer
1066 if (rhs.high == 0) {
1067 if (!div_64bit((uint64_t*)q, &low, (uint64_t*)nom, rhs.low, 2)) {
1069 }
1070 high = 0;
1071 } else {
1072 const uint64_t denom[2] = {rhs.low, rhs.high};
1073 // Written into a separate buffer rather than into low and high directly: the
1074 // numerator is still being read out of them while the division runs.
1075 uint64_t r[2] {};
1076 if (!div_128bit<array_length(nom)>(q, r, nom, denom)) {
1078 }
1079 low = r[0];
1080 high = r[1];
1081 }
1082 return *this;
1083 }
1084 }
1085 /**
1086 * @brief %= operator
1087 * @param x Modulo operand.
1088 * @return This object.
1089 */
1090 template <typename T> FP128_FORCE_INLINE int128_base& operator%=(T x) { return operator%=(int128_base(x)); }
1091 /**
1092 * @brief Shift right this object.
1093 * The signed type shifts arithmetically, replicating the sign bit; the unsigned type shifts
1094 * logically. Both are done without rounding, to match int64_t and uint64_t.
1095 * @param shift Bits to shift. Zero and negative values leave the object unchanged. Values of
1096 * 128 and above produce zero, or -1 for a negative value of the signed type.
1097 * @return This object.
1098 */
1099 FP128_INLINE constexpr int128_base& operator>>=(int32_t shift) noexcept
1100 {
1101 if (shift < 1)
1102 return *this;
1103
1104 if constexpr (is_signed) {
1105 const int64_t temp = static_cast<int64_t>(high);
1106 const uint64_t sign_bits = static_cast<uint64_t>(temp >> 63); // all zeros or all ones
1107
1108 // 1-63 bit shift - most common
1109 if (shift < 64) {
1110 low = FP128_SHIFTRIGHT128(low, high, static_cast<uint8_t>(shift));
1111 high = static_cast<uint64_t>(temp >> shift);
1112 }
1113 // the whole value shifts out, leaving nothing but copies of the sign bit. Without this
1114 // check the shift below would be taken modulo 64 by the hardware.
1115 else if (shift > 127) {
1116 low = high = sign_bits;
1117 } else {
1118 low = static_cast<uint64_t>(temp >> (shift - 64));
1119 high = sign_bits;
1120 }
1121 } else {
1122 // 1-63 bit shift - most common
1123 if (shift < 64) {
1124 low = FP128_SHIFTRIGHT128(low, high, static_cast<uint8_t>(shift));
1125 high >>= shift;
1126 }
1127 // the whole value shifts out. Without this check the shift below would be taken modulo 64
1128 // by the hardware and produce a non zero result.
1129 else if (shift > 127) {
1130 low = high = 0;
1131 } else {
1132 low = high >> (shift - 64);
1133 high = 0;
1134 }
1135 }
1136 return *this;
1137 }
1138 /**
1139 * @brief Shift left this object.
1140 * @param shift Bits to shift. Zero and negative values leave the object unchanged,
1141 * values of 128 and above produce zero.
1142 * @return This object.
1143 */
1144 FP128_INLINE constexpr int128_base& operator<<=(int32_t shift) noexcept
1145 {
1146 if (shift < 1)
1147 return *this;
1148 if (shift < 64) {
1149 high = FP128_SHIFTLEFT128(low, high, static_cast<uint8_t>(shift));
1150 low <<= shift;
1151 }
1152 // the whole value shifts out. Without this check the shift below would be taken modulo 64
1153 // by the hardware and produce a non zero result.
1154 else if (shift > 127) {
1155 low = high = 0;
1156 } else {
1157 high = low << (shift - 64);
1158 low = 0;
1159 }
1160 return *this;
1161 }
1162 /**
1163 * @brief Bitwise AND=
1164 * @param rhs AND mask.
1165 * @return This object.
1166 */
1168 {
1169 low &= rhs.low;
1170 high &= rhs.high;
1171 return *this;
1172 }
1173 /**
1174 * @brief Bitwise AND=
1175 * @param rhs AND mask.
1176 * @return This object.
1177 */
1178 template <typename T> FP128_FORCE_INLINE constexpr int128_base& operator&=(const T& rhs) noexcept { return operator&=(int128_base(rhs)); }
1179 /**
1180 * @brief Bitwise OR=
1181 * @param rhs OR mask.
1182 * @return This object.
1183 */
1185 {
1186 low |= rhs.low;
1187 high |= rhs.high;
1188 return *this;
1189 }
1190 /**
1191 * @brief Bitwise OR=
1192 * @param rhs OR mask.
1193 * @return This object.
1194 */
1195 template <typename T> FP128_FORCE_INLINE constexpr int128_base& operator|=(const T& rhs) noexcept { return operator|=(int128_base(rhs)); }
1196 /**
1197 * @brief Bitwise XOR=
1198 * @param rhs XOR mask.
1199 * @return This object.
1200 */
1202 {
1203 low ^= rhs.low;
1204 high ^= rhs.high;
1205 return *this;
1206 }
1207 /**
1208 * @brief Bitwise XOR=
1209 * @param rhs XOR mask.
1210 * @return This object.
1211 */
1212 template <typename T> FP128_FORCE_INLINE constexpr int128_base& operator^=(const T& rhs) noexcept { return operator^=(int128_base(rhs)); }
1213 /**
1214 * @brief Prefix ++ operation (++a)
1215 * @return This object.
1216 */
1218 {
1219 *this += 1;
1220 return *this;
1221 }
1222 /**
1223 * @brief Postfix ++ operation (a++)
1224 * @return This object.
1225 */
1226 FP128_FORCE_INLINE constexpr int128_base operator++(int32_t) noexcept
1227 {
1228 int128_base temp(*this);
1229 ++*this; // call the prefix implementation
1230 return temp;
1231 }
1232 /**
1233 * @brief Prefix -- operation (--a)
1234 * @return This object.
1235 */
1237 {
1238 *this -= 1;
1239 return *this;
1240 }
1241 /**
1242 * @brief Postfix -- operation (a--)
1243 * @return This object.
1244 */
1245 FP128_FORCE_INLINE constexpr int128_base operator--(int32_t) noexcept
1246 {
1247 int128_base temp(*this);
1248 --*this; // call the prefix implementation
1249 return temp;
1250 }
1251
1252 //
1253 // unary operations
1254 //
1255 /**
1256 * @brief Convert to bool
1257 */
1258 [[nodiscard]] FP128_FORCE_INLINE constexpr operator bool() const noexcept { return high != 0 || low != 0; }
1259 /**
1260 * @brief Logical not (!). Opposite of operator bool.
1261 */
1262 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator!() const noexcept { return high == 0 && low == 0; }
1263 /**
1264 * @brief Bitwise not (~).
1265 */
1266 [[nodiscard]] FP128_FORCE_INLINE constexpr int128_base operator~() const noexcept
1267 {
1268 int128_base temp(*this);
1269 temp.high = ~high;
1270 temp.low = ~low;
1271 return temp;
1272 }
1273 /**
1274 * @brief Unary +. Returns a copy of the object.
1275 */
1276 [[nodiscard]] FP128_FORCE_INLINE constexpr int128_base operator+() const noexcept
1277 {
1278 int128_base temp(*this);
1279 return temp;
1280 }
1281 /**
1282 * @brief Unary -. Returns a copy of the object with sign inverted.
1283 * Performs a 2's complement operation just like the native integer types
1284 */
1285 [[nodiscard]] FP128_FORCE_INLINE constexpr int128_base operator-() const noexcept
1286 {
1287 int128_base temp = *this;
1288 twos_complement128(temp.low, temp.high);
1289 return temp;
1290 }
1291
1292 //
1293 // Comparison operators
1294 //
1295 // An integral operand is widened to int128_base and compared at 128 bits. A floating point
1296 // operand is compared as the real number it is, see CompareFloating(): 2 == 2.5 is false, a
1297 // NaN is unordered (only != holds), and values beyond the range order beyond every value.
1298 //
1299 /**
1300 * @brief Compare logical/bitwise equal.
1301 * @param rhs Righthand operand
1302 * @return True if this and rhs are equal.
1303 */
1304 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator==(const int128_base& rhs) const noexcept { return high == rhs.high && low == rhs.low; }
1305 /**
1306 * @brief Compare logical/bitwise equal.
1307 * @param rhs Righthand operand
1308 * @return True if this and rhs are equal.
1309 */
1310 template <typename T> [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator==(const T& rhs) const noexcept
1311 {
1312 if constexpr (std::is_floating_point_v<T>) {
1313 const int32_t r = CompareFloating(rhs);
1314 return r == 0;
1315 } else {
1316 return *this == int128_base(rhs);
1317 }
1318 }
1319 /**
1320 * @brief Return true when objects are not equal. Can be used as logical XOR.
1321 * @param rhs Righthand operand.
1322 * @return True of not equal.
1323 */
1324 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator!=(const int128_base& rhs) const noexcept { return low != rhs.low || high != rhs.high; }
1325 /**
1326 * @brief Return true when objects are not equal. Can be used as logical XOR.
1327 * @param rhs Righthand operand.
1328 * @return True of not equal.
1329 */
1330 template <typename T> [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator!=(const T& rhs) const noexcept
1331 {
1332 if constexpr (std::is_floating_point_v<T>) {
1333 const int32_t r = CompareFloating(rhs);
1334 return r != 0;
1335 } else {
1336 return *this != int128_base(rhs);
1337 }
1338 }
1339 /**
1340 * @brief Return true if this object is small than the rhs
1341 * @param rhs Righthand operand.
1342 * @return True when this object is smaller.
1343 */
1344 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator<(const int128_base& rhs) const noexcept
1345 {
1346 if constexpr (is_signed) {
1347 const bool sign = is_negative();
1348 const bool rhs_sign = rhs.is_negative();
1349 // objects have a different sign
1350 if (sign != rhs_sign) {
1351 return sign;
1352 }
1353 }
1354
1355 // objects have the same sign, or the type is unsigned
1356 return high < rhs.high || (high == rhs.high && low < rhs.low);
1357 }
1358 /**
1359 * @brief Return true if this object is small than the rhs
1360 * @param rhs Righthand operand.
1361 * @return True when this object is smaller.
1362 */
1363 template <typename T> [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator<(const T& rhs) const noexcept
1364 {
1365 if constexpr (std::is_floating_point_v<T>) {
1366 const int32_t r = CompareFloating(rhs);
1367 return r == -1;
1368 } else {
1369 return *this < int128_base(rhs);
1370 }
1371 }
1372 /**
1373 * @brief Return true this object is small or equal than the rhs
1374 * @param rhs Righthand operand.
1375 * @return True when this object is smaller or equal.
1376 */
1377 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator<=(const int128_base& rhs) const noexcept { return !(*this > rhs); }
1378 /**
1379 * @brief Return true this object is small or equal than the rhs
1380 * @param rhs Righthand operand.
1381 * @return True when this object is smaller or equal.
1382 */
1383 template <typename T> [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator<=(const T& rhs) const noexcept
1384 {
1385 if constexpr (std::is_floating_point_v<T>) {
1386 const int32_t r = CompareFloating(rhs);
1387 return r == -1 || r == 0;
1388 } else {
1389 return !(*this > int128_base(rhs));
1390 }
1391 }
1392 /**
1393 * @brief Return true this object is larger than the rhs
1394 * @param rhs Righthand operand.
1395 * @return True when this objext is larger.
1396 */
1397 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator>(const int128_base& rhs) const noexcept
1398 {
1399 if constexpr (is_signed) {
1400 const bool sign = is_negative();
1401 const bool rhs_sign = rhs.is_negative();
1402 // objects have a different sign
1403 if (sign != rhs_sign) {
1404 return rhs_sign;
1405 }
1406 }
1407
1408 // objects have the same sign, or the type is unsigned
1409 return high > rhs.high || (high == rhs.high && low > rhs.low);
1410 }
1411 /**
1412 * @brief Return true this object is larger than the rhs
1413 * @param rhs Righthand operand.
1414 * @return True when this objext is larger.
1415 */
1416 template <typename T> [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator>(const T& rhs) const noexcept
1417 {
1418 if constexpr (std::is_floating_point_v<T>) {
1419 const int32_t r = CompareFloating(rhs);
1420 return r == 1;
1421 } else {
1422 return *this > int128_base(rhs);
1423 }
1424 }
1425 /**
1426 * @brief Return true this object is larger or equal than the rhs
1427 * @param rhs Righthand operand.
1428 * @return True when this objext is larger or equal.
1429 */
1430 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator>=(const int128_base& rhs) const noexcept { return !(*this < rhs); }
1431 /**
1432 * @brief Return true this object is larger or equal than the rhs
1433 * @param rhs Righthand operand.
1434 * @return True when this objext is larger or equal.
1435 */
1436 template <typename T> [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator>=(const T& rhs) const noexcept
1437 {
1438 if constexpr (std::is_floating_point_v<T>) {
1439 const int32_t r = CompareFloating(rhs);
1440 return r == 0 || r == 1;
1441 } else {
1442 return !(*this < int128_base(rhs));
1443 }
1444 }
1445
1446 //
1447 // useful public functions
1448 //
1449 /**
1450 * @brief Returns true if the value is an int (fraction is zero)
1451 * @return True when the fraction is zero.
1452 */
1453 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_int() const noexcept { return true; }
1454 /**
1455 * @brief Returns true if the value is positive (including zero)
1456 * Always true for the unsigned type, which lets the sign tests in the shared code fold away.
1457 * @return True when the value is positive
1458 */
1459 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_positive() const noexcept
1460 {
1461 if constexpr (is_signed) {
1462 return 0ull == high >> 63;
1463 } else {
1464 return true;
1465 }
1466 }
1467 /**
1468 * @brief Returns true if the value negative (smaller than zero)
1469 * Always false for the unsigned type, which lets the sign tests in the shared code fold away.
1470 * @return True when the value is negative
1471 */
1472 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_negative() const noexcept
1473 {
1474 if constexpr (is_signed) {
1475 return 1ull == high >> 63;
1476 } else {
1477 return false;
1478 }
1479 }
1480 /**
1481 * @brief Returns true if the value is zero
1482 * @return Returns true if the value is zero
1483 */
1484 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_zero() const noexcept { return 0 == low && 0 == high; }
1485 /**
1486 * @brief get a specific bit within the 128 data
1487 * @param bit bit to get [0,127]
1488 * @return 0 or 1. Undefined when bit > 127
1489 */
1490 [[nodiscard]] FP128_FORCE_INLINE constexpr int32_t get_bit(uint32_t bit) const noexcept
1491 {
1492 if (bit < 64) {
1493 return FP128_GET_BIT(low, bit);
1494 }
1495 return FP128_GET_BIT(high, bit - 64);
1496 }
1497 /**
1498 * @brief Extracts the low and high QWORD
1499 * @param l Reference to the low QWORD
1500 * @param h Reference to the high QWORD
1501 */
1502 FP128_FORCE_INLINE constexpr void get_components(uint64_t& l, uint64_t& h) const noexcept
1503 {
1504 l = low;
1505 h = high;
1506 }
1507 /**
1508 * @brief Return an instance of int128_base with the value of 1
1509 * @return 1
1510 */
1511 [[nodiscard]] FP128_FORCE_INLINE static constexpr int128_base one() noexcept { return int128_base(1u); }
1512 /**
1513 * @brief Converts this object to a hex C string.
1514 * The returned string is a statically thread-allocated buffer.
1515 * Additional calls to this function from the same thread overwrite the previous result.
1516 * @return C string containing the HEX value of the object.
1517 */
1518 [[nodiscard]] FP128_INLINE char* hex() const noexcept
1519 {
1520 constexpr int buff_size = 35;
1521 static thread_local char str[buff_size];
1522 snprintf(str, buff_size, "0x%016llX%016llX", high, low);
1523 return str;
1524 }
1525
1526 //
1527 // Binary math operators
1528 //
1529 // Each of these applies the compound assignment to the by value left hand side and then returns
1530 // it on a line of its own. The shorter `return lhs OP= rhs;` is equivalent and was what these
1531 // used to say, but it costs MSVC a factor of six on the multiplication: the compound assignment
1532 // returns int128_base&, so the return statement copy constructs the result from an lvalue, and
1533 // MSVC emits that copy as a 16 byte XMM load of the object whose two halves it has just written
1534 // with 8 byte GPR stores. A load that overlaps two narrower stores cannot forward, so every
1535 // evaluation ends in a store forwarding stall of about fifteen cycles - which is five times the
1536 // multiplication itself. Returning the named parameter instead keeps it in registers.
1537 // Clang generates identical code either way. Measured: uint128_t * uint128_t goes from 259M/s
1538 // to 1.73G/s on MSVC 19.51, matching Clang.
1539 //
1540
1541 /**
1542 * @brief Adds 2 values and returns the result.
1543 * @param lhs left hand side operand
1544 * @param rhs Right hand side operand
1545 * @return Result of the operation
1546 */
1547 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator+(int128_base lhs, const T& rhs) noexcept
1548 {
1549 lhs += rhs;
1550 return lhs;
1551 }
1552 /**
1553 * @brief Subtracts 2 values and returns the result.
1554 * @param lhs left hand side operand
1555 * @param rhs Right hand side operand
1556 * @return Result of the operation
1557 */
1558 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator-(int128_base lhs, const T& rhs) noexcept
1559 {
1560 lhs -= rhs;
1561 return lhs;
1562 }
1563 /**
1564 * @brief Multiplies 2 values and returns the result.
1565 *
1566 * Only takes part in overload resolution when the matching compound assignment exists, so an
1567 * unsupported operand is rejected at the call site rather than inside this body. See
1568 * operator*=(T) for which operands those are.
1569 *
1570 * @param lhs left hand side operand
1571 * @param rhs Right hand side operand
1572 * @return Result of the operation
1573 */
1574 template <typename T>
1575 requires requires(int128_base l, const T& r) { l *= r; }
1576 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator*(int128_base lhs, const T& rhs) noexcept
1577 {
1578 lhs *= rhs;
1579 return lhs;
1580 }
1581 /**
1582 * @brief Divides 2 values and returns the result.
1583 *
1584 * Forced inline like every other forwarder here, see FP128_FORCE_INLINE. This one is where the
1585 * cost was first measured: leaving the decision to MSVC under /GL (whole program optimization)
1586 * lands on a round trip through memory worth ~10% of a 128 bit by 64 bit division.
1587 *
1588 * @param lhs left hand side operand
1589 * @param rhs Right hand side operand
1590 * @return Result of the operation
1591 */
1592 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE int128_base operator/(int128_base lhs, const T& rhs)
1593 {
1594 lhs /= rhs;
1595 return lhs;
1596 }
1597 /**
1598 * @brief Performs modulo and returns the result.
1599 *
1600 * @param lhs left hand side operand
1601 * @param rhs Right hand side operand
1602 * @return Result of the operation
1603 */
1604 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE int128_base operator%(int128_base lhs, const T& rhs)
1605 {
1606 lhs %= rhs;
1607 return lhs;
1608 }
1609
1610 //
1611 // Binary math operators
1612 //
1613 /**
1614 * @brief Performs bitwise AND (&).
1615 * @param lhs left hand side operand
1616 * @param rhs Right hand side operand
1617 * @return Result of the operation
1618 */
1619 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator&(int128_base lhs, const T& rhs) noexcept
1620 {
1621 lhs &= rhs;
1622 return lhs;
1623 }
1624 /**
1625 * @brief Performs bitwise OR (|).
1626 * @param lhs left hand side operand
1627 * @param rhs Right hand side operand
1628 * @return Result of the operation
1629 */
1630 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator|(int128_base lhs, const T& rhs) noexcept
1631 {
1632 lhs |= rhs;
1633 return lhs;
1634 }
1635 /**
1636 * @brief Performs bitwise XOR (^).
1637 * @param lhs left hand side operand
1638 * @param rhs Right hand side operand
1639 * @return Result of the operation
1640 */
1641 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator^(int128_base lhs, const T& rhs) noexcept
1642 {
1643 lhs ^= rhs;
1644 return lhs;
1645 }
1646
1647 //
1648 // Binary math operators with the scalar on the left hand side
1649 //
1650 // Without these, an expression like (1 + x) is ambiguous: converting the literal to
1651 // int128_base and converting x to a builtin type are both one user defined conversion, so
1652 // neither overload wins. Restricting the left operand to the arithmetic types keeps these from
1653 // competing with the int128_base on the left versions above, which would otherwise be an
1654 // equally good match.
1655 //
1656
1657 /// @brief Adds a scalar and an int128_base, in that order. @param lhs Left operand @param rhs Right operand @return Result of the operation
1658 template <typename T>
1659 requires std::is_arithmetic_v<T>
1660 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator+(const T& lhs, const int128_base& rhs) noexcept
1661 {
1662 return int128_base(lhs) += rhs;
1663 }
1664 /// @brief Subtracts an int128_base from a scalar. @param lhs Left operand @param rhs Right operand @return Result of the operation
1665 template <typename T>
1666 requires std::is_arithmetic_v<T>
1667 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator-(const T& lhs, const int128_base& rhs) noexcept
1668 {
1669 return int128_base(lhs) -= rhs;
1670 }
1671 /// @brief Multiplies a scalar and an int128_base, in that order. @param lhs Left operand @param rhs Right operand @return Result of the operation
1672 template <typename T>
1673 requires std::is_arithmetic_v<T>
1674 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator*(const T& lhs, const int128_base& rhs) noexcept
1675 {
1676 return int128_base(lhs) *= rhs;
1677 }
1678 /// @brief Divides a scalar by an int128_base. @param lhs Left operand @param rhs Right operand @return Result of the operation
1679 template <typename T>
1680 requires std::is_arithmetic_v<T>
1681 [[nodiscard]] friend FP128_FORCE_INLINE int128_base operator/(const T& lhs, const int128_base& rhs)
1682 {
1683 return int128_base(lhs) /= rhs;
1684 }
1685 /// @brief Performs modulo of a scalar by an int128_base. @param lhs Left operand @param rhs Right operand @return Result of the operation
1686 template <typename T>
1687 requires std::is_arithmetic_v<T>
1688 [[nodiscard]] friend FP128_FORCE_INLINE int128_base operator%(const T& lhs, const int128_base& rhs)
1689 {
1690 return int128_base(lhs) %= rhs;
1691 }
1692 /// @brief Performs bitwise AND of a scalar and an int128_base. @param lhs Left operand @param rhs Right operand @return Result of the operation
1693 template <typename T>
1694 requires std::is_arithmetic_v<T>
1695 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator&(const T& lhs, const int128_base& rhs) noexcept
1696 {
1697 return int128_base(lhs) &= rhs;
1698 }
1699 /// @brief Performs bitwise OR of a scalar and an int128_base. @param lhs Left operand @param rhs Right operand @return Result of the operation
1700 template <typename T>
1701 requires std::is_arithmetic_v<T>
1702 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator|(const T& lhs, const int128_base& rhs) noexcept
1703 {
1704 return int128_base(lhs) |= rhs;
1705 }
1706 /// @brief Performs bitwise XOR of a scalar and an int128_base. @param lhs Left operand @param rhs Right operand @return Result of the operation
1707 template <typename T>
1708 requires std::is_arithmetic_v<T>
1709 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator^(const T& lhs, const int128_base& rhs) noexcept
1710 {
1711 return int128_base(lhs) ^= rhs;
1712 }
1713 /**
1714 * @brief Shifts a scalar left by an int128_base shift count.
1715 *
1716 * The left operand is widened to int128_base first, so the result is 128 bit rather than the
1717 * builtin type of lhs. This is what makes (1 << n) with a large n produce the expected power of
1718 * two instead of the undefined behavior a builtin shift past the operand width would have.
1719 *
1720 * @param lhs Left operand, the value being shifted
1721 * @param rhs Right operand, the shift count. Only its low 32 bits are used.
1722 * @return Result of the operation
1723 */
1724 template <typename T>
1725 requires std::is_arithmetic_v<T>
1726 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator<<(const T& lhs, const int128_base& rhs) noexcept
1727 {
1728 return int128_base(lhs) <<= static_cast<int32_t>(rhs);
1729 }
1730 /**
1731 * @brief Shifts a scalar right by an int128_base shift count.
1732 * The left operand is widened to int128_base first, see operator<< above.
1733 * @param lhs Left operand, the value being shifted
1734 * @param rhs Right operand, the shift count. Only its low 32 bits are used.
1735 * @return Result of the operation
1736 */
1737 template <typename T>
1738 requires std::is_arithmetic_v<T>
1739 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base operator>>(const T& lhs, const int128_base& rhs) noexcept
1740 {
1741 return int128_base(lhs) >>= static_cast<int32_t>(rhs);
1742 }
1743
1744 //
1745 // Comparison operators with the scalar on the left hand side
1746 //
1747 // The member comparisons above only cover an int128_base on the left. Without these, an
1748 // expression like (1 == x) has nothing but the builtin comparisons to choose from, and the
1749 // seven conversion operators of int128_base make every one of them equally good, so the call is
1750 // ambiguous. Widening the scalar keeps the comparison exact at 128 bits instead of narrowing
1751 // the object down to whichever builtin type the compiler happened to pick. A floating point
1752 // scalar is not widened, which would truncate it, but compared as a real number by
1753 // CompareFloating(), as the member comparisons do.
1754 //
1755
1756 /// @brief Compares a scalar and an int128_base for equality. @param lhs Left operand @param rhs Right operand @return True when the two are equal
1757 template <typename T>
1758 requires std::is_arithmetic_v<T>
1759 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator==(const T& lhs, const int128_base& rhs) noexcept
1760 {
1761 if constexpr (std::is_floating_point_v<T>) {
1762 // r orders rhs against lhs, the reverse of the operands here
1763 const int32_t r = rhs.CompareFloating(lhs);
1764 return r == 0;
1765 } else {
1766 return int128_base(lhs) == rhs;
1767 }
1768 }
1769 /// @brief Compares a scalar and an int128_base for inequality. @param lhs Left operand @param rhs Right operand @return True when the two differ
1770 template <typename T>
1771 requires std::is_arithmetic_v<T>
1772 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator!=(const T& lhs, const int128_base& rhs) noexcept
1773 {
1774 if constexpr (std::is_floating_point_v<T>) {
1775 // r orders rhs against lhs, the reverse of the operands here
1776 const int32_t r = rhs.CompareFloating(lhs);
1777 return r != 0;
1778 } else {
1779 return int128_base(lhs) != rhs;
1780 }
1781 }
1782 /// @brief Returns true when a scalar is smaller than an int128_base. @param lhs Left operand @param rhs Right operand @return True when lhs is smaller
1783 template <typename T>
1784 requires std::is_arithmetic_v<T>
1785 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<(const T& lhs, const int128_base& rhs) noexcept
1786 {
1787 if constexpr (std::is_floating_point_v<T>) {
1788 // r orders rhs against lhs, the reverse of the operands here
1789 const int32_t r = rhs.CompareFloating(lhs);
1790 return r == 1;
1791 } else {
1792 return int128_base(lhs) < rhs;
1793 }
1794 }
1795 /// @brief Returns true when a scalar is smaller or equal to an int128_base. @param lhs Left operand @param rhs Right operand @return True when lhs is smaller or equal
1796 template <typename T>
1797 requires std::is_arithmetic_v<T>
1798 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<=(const T& lhs, const int128_base& rhs) noexcept
1799 {
1800 if constexpr (std::is_floating_point_v<T>) {
1801 // r orders rhs against lhs, the reverse of the operands here
1802 const int32_t r = rhs.CompareFloating(lhs);
1803 return r == 0 || r == 1;
1804 } else {
1805 return int128_base(lhs) <= rhs;
1806 }
1807 }
1808 /// @brief Returns true when a scalar is larger than an int128_base. @param lhs Left operand @param rhs Right operand @return True when lhs is larger
1809 template <typename T>
1810 requires std::is_arithmetic_v<T>
1811 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>(const T& lhs, const int128_base& rhs) noexcept
1812 {
1813 if constexpr (std::is_floating_point_v<T>) {
1814 // r orders rhs against lhs, the reverse of the operands here
1815 const int32_t r = rhs.CompareFloating(lhs);
1816 return r == -1;
1817 } else {
1818 return int128_base(lhs) > rhs;
1819 }
1820 }
1821 /// @brief Returns true when a scalar is larger or equal to an int128_base. @param lhs Left operand @param rhs Right operand @return True when lhs is larger or equal
1822 template <typename T>
1823 requires std::is_arithmetic_v<T>
1824 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>=(const T& lhs, const int128_base& rhs) noexcept
1825 {
1826 if constexpr (std::is_floating_point_v<T>) {
1827 // r orders rhs against lhs, the reverse of the operands here
1828 const int32_t r = rhs.CompareFloating(lhs);
1829 return r == -1 || r == 0;
1830 } else {
1831 return int128_base(lhs) >= rhs;
1832 }
1833 }
1834
1835 //
1836 // Various math functions, implemented as friend functions
1837 //
1838 // These are hidden friends: they are found by argument dependent lookup only, never by
1839 // ordinary unqualified lookup. That is what keeps abs() below from hiding ::abs() for the
1840 // builtin types inside namespace fp128.
1841 //
1842
1843 /**
1844 * @brief Calculates the absolute value of x.
1845 * Only declared for the signed instantiation. An unqualified abs() on an unsigned value keeps
1846 * resolving the way it does today.
1847 * @param x input value.
1848 * @return |x|
1849 */
1850 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base abs(const int128_base& x) noexcept
1851 requires IsSigned
1852 {
1853 return x.is_positive() ? x : -x;
1854 }
1855 /**
1856 * @brief Calculates the square of a value. i.e. x^2
1857 *
1858 * Faster than x * x and bit identical to it, see int128_base::square().
1859 *
1860 * @param x Value to square
1861 * @return x^2, truncated to 128 bit
1862 */
1863 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int128_base sqr(int128_base x) noexcept { return x.square(); }
1864 /**
1865 * @brief Calculates the left zero count of value x.
1866 * @param x input value.
1867 * @return lzc (uint32_t) of the result.
1868 */
1869 [[nodiscard]] friend FP128_FORCE_INLINE constexpr uint64_t lzcnt128(const int128_base& x) noexcept
1870 {
1871 return (x.high != 0) ? lzcnt64(x.high) : 64 + lzcnt64(x.low);
1872 }
1873 /**
1874 * @brief Calculates the square root using Newton's method.
1875 * Based on the book "Math toolkit for real time programming" by Jack W. Crenshaw
1876 * @param x Value to calculate the root of
1877 * @return Square root of (x) rounded down to the nearest integer, zero when x <= 0.
1878 */
1879 [[nodiscard]] friend FP128_INLINE uint64_t sqrt(const int128_base& x) noexcept
1880 {
1881 // zero has to be rejected here as well as the negatives. log2 throws on a zero input and
1882 // this function is noexcept, so letting it through would terminate the process.
1883 // The negative test is a compile time false for the unsigned instantiation.
1884 if (x.is_negative() || x.is_zero())
1885 return 0;
1886
1887 // an msb at bit zero means the value is 1, which is its own root and would make the
1888 // initial guess below zero
1889 const auto expo = static_cast<uint32_t>(log2(x));
1890 if (expo == 0) {
1891 return 1;
1892 }
1893
1895 int128_base e, temp;
1896 root <<= ((expo + 1) >> 1);
1897
1898 // Newton iterations to reduce the error
1899 do {
1900 temp = x / root;
1901 // working with unsigned numbers, must keep the below positive at all times
1902 e = ((root > temp) ? (root - temp) : (temp - root)) >> 1;
1903 root = (root + temp) >> 1;
1904 } while (e);
1905
1906 return root;
1907 }
1908 /**
1909 * @brief Calculates the Log base 2 of x: log2(x)
1910 * Rounding is always towards zero so the maximum error is close to 1.
1911 * @param x The number to perform log2 on.
1912 * @return log2(x), which is also the bit position of the msb.
1913 * @throws std::domain_error when x is zero, or negative for the signed type.
1914 */
1915 [[nodiscard]] friend FP128_FORCE_INLINE constexpr uint64_t log2(const int128_base& x)
1916 {
1917 if (x.is_negative() || x.is_zero()) {
1918 throw std::domain_error("Math domain error! Function accepts positive, non-zero values only.");
1919 }
1920
1921 return 127ull - lzcnt128(x);
1922 }
1923 /**
1924 * @brief Calculates the natural Log (base e) of x: log(x), rounded down to the nearest integer.
1925 * @param x The number to perform log on.
1926 * @return log(x)
1927 * @throws std::domain_error when x is zero, or negative for the signed type.
1928 */
1929 [[nodiscard]] friend FP128_FORCE_INLINE uint64_t log(const int128_base& x)
1930 {
1931 if (x.is_negative() || x.is_zero()) {
1932 throw std::domain_error("Math domain error! Function accepts positive, non-zero values only.");
1933 }
1934
1935 // The table below holds the value of various powers of e (~2.718), index i holds
1936 // ceil(pow(e, i)). That is the smallest integer whose log is i: e^i is never itself an
1937 // integer, so an integer x satisfies x >= e^i exactly when x >= ceil(e^i). Every entry
1938 // therefore has to be exact to the last digit, a value one too large misclassifies the
1939 // boundary itself and one too small misclassifies everything up to the true boundary.
1940 // The entries are produced with exact arithmetic rather than pow(), which loses the low
1941 // digits well before e^88.<BR>
1942 // Being a function local static with an initializer, the language guarantees its
1943 // construction happens once even when several threads race to get here.
1944 static const int128_base lan_table[] = {
1945 "1", // e^0
1946 "3", // e^1
1947 "8", // e^2
1948 "21", // e^3
1949 "55", // e^4
1950 "149", // e^5
1951 "404", // e^6
1952 "1097", // e^7
1953 "2981", // e^8
1954 "8104", // e^9
1955 "22027", // e^10
1956 "59875", // e^11
1957 "162755", // e^12
1958 "442414", // e^13
1959 "1202605", // e^14
1960 "3269018", // e^15
1961 "8886111", // e^16
1962 "24154953", // e^17
1963 "65659970", // e^18
1964 "178482301", // e^19
1965 "485165196", // e^20
1966 "1318815735", // e^21
1967 "3584912847", // e^22
1968 "9744803447", // e^23
1969 "26489122130", // e^24
1970 "72004899338", // e^25
1971 "195729609429", // e^26
1972 "532048240602", // e^27
1973 "1446257064292", // e^28
1974 "3931334297145", // e^29
1975 "10686474581525", // e^30
1976 "29048849665248", // e^31
1977 "78962960182681", // e^32
1978 "214643579785917", // e^33
1979 "583461742527455", // e^34
1980 "1586013452313431", // e^35
1981 "4311231547115196", // e^36
1982 "11719142372802612", // e^37
1983 "31855931757113757", // e^38
1984 "86593400423993747", // e^39
1985 "235385266837019986", // e^40
1986 "639843493530054950", // e^41
1987 "1739274941520501048", // e^42
1988 "4727839468229346562", // e^43
1989 "12851600114359308276", // e^44
1990 "34934271057485095349", // e^45
1991 "94961194206024488746", // e^46
1992 "258131288619006739624", // e^47
1993 "701673591209763173866", // e^48
1994 "1907346572495099690526", // e^49
1995 "5184705528587072464088", // e^50
1996 "14093490824269387964493", // e^51
1997 "38310080007165768493036", // e^52
1998 "104137594330290877971835", // e^53
1999 "283075330327469390044207", // e^54
2000 "769478526514201713818275", // e^55
2001 "2091659496012996153907072", // e^56
2002 "5685719999335932222640349", // e^57
2003 "15455389355901039303530767", // e^58
2004 "42012104037905142549565935", // e^59
2005 "114200738981568428366295719", // e^60
2006 "310429793570191990870734215", // e^61
2007 "843835666874145448907332949", // e^62
2008 "2293783159469609879099352841", // e^63
2009 "6235149080811616882909238709", // e^64
2010 "16948892444103337141417836115", // e^65
2011 "46071866343312915426773184429", // e^66
2012 "125236317084221378051352196075", // e^67
2013 "340427604993174052137690718701", // e^68
2014 "925378172558778760024239791669", // e^69
2015 "2515438670919167006265781174253", // e^70
2016 "6837671229762743866755892826678", // e^71
2017 "18586717452841279803403701812546", // e^72
2018 "50523936302761041945570383321858", // e^73
2019 "137338297954017618778418852980854", // e^74
2020 "373324199679900164025490831726471", // e^75
2021 "1014800388113888727832461784131717", // e^76
2022 "2758513454523170206286469819902662", // e^77
2023 "7498416996990120434675630591224061", // e^78
2024 "20382810665126687668323137537172633", // e^79
2025 "55406223843935100525711733958316613", // e^80
2026 "150609731458503054835259413016767499", // e^81
2027 "409399696212745469666091422932782905", // e^82
2028 "1112863754791759412087071478183940806", // e^83
2029 "3025077322201142338266566396443428743", // e^84
2030 "8223012714622913510304328016407774696", // e^85
2031 "22352466037347150474430657323327147399", // e^86
2032 "60760302250568721495223289381302760753", // e^87
2033 "165163625499400185552832979626485876707" // e^88
2034 };
2035 static constexpr uint64_t lan_table_len = array_length(lan_table);
2036 if (x < 3)
2037 return 0;
2038 if (x >= lan_table[lan_table_len - 1])
2039 return lan_table_len - 1;
2040
2041 // binary search the result
2042 uint64_t l = 0, h = lan_table_len - 1, res = (h + l) >> 1;
2043
2044 while (l < h) {
2045 if (x < lan_table[res]) {
2046 h = res;
2047 } else if (l == res)
2048 break;
2049 else {
2050 l = res;
2051 }
2052 res = (h + l) >> 1;
2053 }
2054 return res;
2055 }
2056 /**
2057 * @brief Calculates Log base 10 of x: log10(x), rounded down to the nearest integer.
2058 * @param x The number to perform log on.
2059 * @return log10(x)
2060 * @throws std::domain_error when x is zero, or negative for the signed type.
2061 */
2062 [[nodiscard]] friend FP128_FORCE_INLINE uint64_t log10(const int128_base& x)
2063 {
2064 if (x.is_negative() || x.is_zero()) {
2065 throw std::domain_error("Math domain error! Function accepts positive, non-zero values only.");
2066 }
2067
2068 static constexpr uint64_t log10_max = 38; // 10^38 is the largest power of ten below 2^127
2069 // Holds every power of ten that fits in 128 bit. Building it inside the initializer of a
2070 // function local static makes the first call thread safe: the language guarantees that
2071 // concurrent callers block until the initialization finishes. Filling a plain static array
2072 // behind an 'is it still zero' check does not, both threads can pass the check at once.
2073 static const auto log10_table = []() {
2074 std::array<int128_base, log10_max + 1> table;
2075 table[0] = 1ull;
2076 for (uint32_t i = 1u; i <= log10_max; ++i) {
2077 table[i] = table[i - 1] * 10ull;
2078 }
2079 return table;
2080 }();
2081
2082 if (x >= log10_table[log10_max])
2083 return log10_max;
2084
2085 // binary search the result
2086 uint64_t l = 0, h = log10_max, res = (h + l) >> 1;
2087
2088 while (l < h) {
2089 if (x < log10_table[res]) {
2090 h = res;
2091 } else if (l == res)
2092 break;
2093 else {
2094 l = res;
2095 }
2096 res = (h + l) >> 1;
2097 }
2098 return res;
2099 }
2100 /**
2101 * @brief Calculates x to the power of y.
2102 * @param x Base value
2103 * @param y Exponent
2104 * @return x to the power of y
2105 */
2106 [[nodiscard]] friend FP128_INLINE constexpr int128_base pow(const int128_base& x, uint32_t y) noexcept
2107 {
2108 // zero power always yields 1
2109 // Even if x is zero! Same behavior as pow(double, double) but different from Python which returns zero.
2110 if (y == 0)
2111 return 1;
2112
2113 // special case where base is zero
2114 if (!x)
2115 return x;
2116
2117 int128_base res = 1;
2118 int128_base b = x;
2119 while (y > 0) {
2120 if (y & 1)
2121 res *= b;
2122 y >>= 1;
2123 b.square();
2124 }
2125 return res;
2126 }
2127}; // class int128_base
2128
2129
2130/**
2131 * @brief Writes a 128 bit integer to a stream, honouring its width, fill and adjustment.
2132 *
2133 * The value is always written in decimal: that is the conversion the type provides, and a stream's
2134 * hex and oct flags have no counterpart in it.
2135 */
2136template <bool IsSigned> inline std::ostream& operator<<(std::ostream& os, const int128_base<IsSigned>& value)
2137{
2138 std::string text = static_cast<std::string>(value);
2139 if ((os.flags() & std::ios_base::showpos) && !text.empty() && text[0] != '-')
2140 text.insert(text.begin(), '+');
2141
2142 const std::streamsize width = os.width();
2143 os.width(0);
2144 if (static_cast<std::streamsize>(text.size()) < width) {
2145 const size_t padding = static_cast<size_t>(width) - text.size();
2146 const std::ios_base::fmtflags adjust = os.flags() & std::ios_base::adjustfield;
2147 if (adjust == std::ios_base::left)
2148 text.append(padding, os.fill());
2149 else if (adjust == std::ios_base::internal && !text.empty() && (text[0] == '-' || text[0] == '+'))
2150 text.insert(1, padding, os.fill());
2151 else
2152 text.insert(0, padding, os.fill());
2153 }
2154 return os << text;
2155}
2156
2157/**
2158 * @brief Reads a 128 bit integer from a stream, the way the builtin integer extractors do.
2159 *
2160 * Reads an optional sign and the digits that follow it, and stops at the first character that is
2161 * not one, leaving it in the stream: "12,34" gives 12 and leaves ",34". The digits are decimal, or
2162 * hexadecimal after an 0x prefix; with std::hex or std::oct set they are read in that base, the
2163 * prefix being optional for hex. A minus sign before an unsigned value wraps it around, as
2164 * strtoull does.
2165 *
2166 * Failure sets failbit, as for a builtin integer: no digits at all - "abc", or "0x" with nothing
2167 * after it - stores zero, and a value outside the type stores the nearest end of its range, max()
2168 * or min(). Leading white space is skipped unless skipws is off. This used to read a whole white
2169 * space delimited token through the string constructor, which never failed: "abc" read as zero
2170 * and an overflow wrapped silently.
2171 */
2172template <bool IsSigned> inline std::istream& operator>>(std::istream& is, int128_base<IsSigned>& value)
2173{
2174 const std::istream::sentry sentry(is);
2175 if (!sentry)
2176 return is;
2177
2178 using magnitude_type = int128_base<false>;
2179 using traits = std::char_traits<char>;
2180 std::streambuf* const buffer = is.rdbuf();
2181 int c = buffer->sgetc();
2182 const auto next = [&]() {
2183 buffer->sbumpc();
2184 c = buffer->sgetc();
2185 };
2186 const auto digit_value = [](int ch) -> int {
2187 if (ch >= '0' && ch <= '9')
2188 return ch - '0';
2189 if (ch >= 'a' && ch <= 'f')
2190 return ch - 'a' + 10;
2191 if (ch >= 'A' && ch <= 'F')
2192 return ch - 'A' + 10;
2193 return 99;
2194 };
2195
2196 bool negative = false;
2197 if (c == '+' || c == '-') {
2198 negative = (c == '-');
2199 next();
2200 }
2201
2202 const std::ios_base::fmtflags basefield = is.flags() & std::ios_base::basefield;
2203 uint32_t base = (basefield == std::ios_base::hex) ? 16u : ((basefield == std::ios_base::oct) ? 8u : 10u);
2204 bool any_digit = false;
2205 if (base != 8 && c == '0') {
2206 // a leading zero is a digit in its own right, unless an x turns it into the hex prefix
2207 next();
2208 any_digit = true;
2209 if (c == 'x' || c == 'X') {
2210 next();
2211 base = 16;
2212 any_digit = false;
2213 }
2214 }
2215
2216 // The magnitude may reach 2^127 for a negative signed value and 2^128 - 1 for an unsigned one.
2217 const magnitude_type limit = IsSigned ? (negative ? magnitude_type(0, 1ull << 63) : magnitude_type(UINT64_MAX, UINT64_MAX >> 1))
2218 : magnitude_type(UINT64_MAX, UINT64_MAX);
2219 magnitude_type magnitude;
2220 bool overflow = false;
2221 while (c != traits::eof() && digit_value(c) < static_cast<int>(base)) {
2222 const uint32_t digit = static_cast<uint32_t>(digit_value(c));
2223 if (!overflow) {
2224 if (magnitude > (limit - magnitude_type(digit)) / magnitude_type(base)) {
2225 overflow = true;
2226 } else {
2227 magnitude = magnitude * magnitude_type(base) + magnitude_type(digit);
2228 }
2229 }
2230 any_digit = true;
2231 next();
2232 }
2233 if (c == traits::eof()) {
2234 is.setstate(std::ios_base::eofbit);
2235 }
2236
2237 if (!any_digit) {
2238 value = int128_base<IsSigned>();
2239 is.setstate(std::ios_base::failbit);
2240 return is;
2241 }
2242 if (overflow) {
2243 value = (IsSigned && negative) ? int128_base<IsSigned>(0, 1ull << 63) : int128_base<IsSigned>(UINT64_MAX, IsSigned ? (UINT64_MAX >> 1) : UINT64_MAX);
2244 is.setstate(std::ios_base::failbit);
2245 return is;
2246 }
2247
2248 uint64_t low = 0, high = 0;
2249 magnitude.get_components(low, high);
2250 if (negative) {
2251 twos_complement128(low, high);
2252 }
2253 value = int128_base<IsSigned>(low, high);
2254 return is;
2255}
2256
2257} // namespace fp128
2258
2259
2260
2261namespace std
2262{
2263/**
2264 * @brief Numeric properties of the 128 bit integer types.
2265 *
2266 * Specialized so that generic code written against a builtin integer - anything reaching for
2267 * numeric_limits<T>::max() to seed a minimum, or for digits10 to size a buffer - compiles and
2268 * behaves correctly when instantiated with int128_t or uint128_t.
2269 *
2270 * The const, volatile and const volatile forms need no specialization of their own: <limits>
2271 * already defines numeric_limits<cv T> to have the members of numeric_limits<T>.
2272 */
2273template <bool IsSigned> class numeric_limits<fp128::int128_base<IsSigned>>
2274{
2275 using value_type = fp128::int128_base<IsSigned>;
2276
2277public:
2278 static constexpr bool is_specialized = true;
2279 static constexpr bool is_signed = IsSigned;
2280 static constexpr bool is_integer = true;
2281 static constexpr bool is_exact = true;
2282 static constexpr bool has_infinity = false;
2283 static constexpr bool has_quiet_NaN = false;
2284 static constexpr bool has_signaling_NaN = false;
2285 // has_denorm and has_denorm_loss are deprecated since C++23 but remain part of the interface a
2286 // generic caller may read, so they are provided.
2288 static constexpr bool has_denorm_loss = false;
2289 static constexpr float_denorm_style has_denorm = denorm_absent;
2291 static constexpr float_round_style round_style = round_toward_zero;
2292 static constexpr bool is_iec559 = false;
2293 static constexpr bool is_bounded = true;
2294 /**
2295 * @brief Both types wrap around: +, - and * keep the low 128 bits of the exact result, which
2296 * differs from it by a multiple of 2^128 = max() - min() + 1.
2297 *
2298 * The builtin signed integers report false only because their overflow is undefined. Here it
2299 * is defined for the signed type as well, and the two's complement bit pattern of a negative
2300 * value is its residue modulo 2^128.
2301 */
2302 static constexpr bool is_modulo = true;
2303 /// @brief Division by zero throws std::logic_error rather than producing a value.
2304 static constexpr bool traps = true;
2305 static constexpr bool tinyness_before = false;
2306
2307 /// @brief Value bits, which excludes the sign bit for the signed type.
2308 static constexpr int digits = IsSigned ? 127 : 128;
2309 /// @brief Decimal digits that can be represented without change: floor(digits * log10(2)),
2310 /// which is 38 for both 127 and 128 bits.
2311 static constexpr int digits10 = 38;
2312 static constexpr int max_digits10 = 0;
2313 static constexpr int radix = 2;
2314 static constexpr int min_exponent = 0;
2315 static constexpr int max_exponent = 0;
2316 static constexpr int min_exponent10 = 0;
2317 static constexpr int max_exponent10 = 0;
2318
2319 [[nodiscard]] static constexpr value_type min() noexcept
2320 {
2321 // The signed minimum is the sign bit on its own; the unsigned one is zero.
2322 return IsSigned ? value_type(0ull, 1ull << 63) : value_type(0ull, 0ull);
2323 }
2324 [[nodiscard]] static constexpr value_type max() noexcept
2325 {
2326 return IsSigned ? value_type(UINT64_MAX, UINT64_MAX >> 1) : value_type(UINT64_MAX, UINT64_MAX);
2327 }
2328 [[nodiscard]] static constexpr value_type lowest() noexcept { return min(); }
2329 [[nodiscard]] static constexpr value_type epsilon() noexcept { return value_type(); }
2330 [[nodiscard]] static constexpr value_type round_error() noexcept { return value_type(); }
2331 [[nodiscard]] static constexpr value_type infinity() noexcept { return value_type(); }
2332 [[nodiscard]] static constexpr value_type quiet_NaN() noexcept { return value_type(); }
2333 [[nodiscard]] static constexpr value_type signaling_NaN() noexcept { return value_type(); }
2334 [[nodiscard]] static constexpr value_type denorm_min() noexcept { return value_type(); }
2335};
2336
2337/// @brief Hash support, so a 128 bit integer can be a key in an unordered container.
2338template <bool IsSigned> struct hash<fp128::int128_base<IsSigned>>
2339{
2340 [[nodiscard]] size_t operator()(const fp128::int128_base<IsSigned>& value) const noexcept
2341 {
2342 uint64_t low = 0, high = 0;
2343 value.get_components(low, high);
2344
2345 // splitmix64's finalizer over the two halves
2346 uint64_t state = low + 0x9E3779B97F4A7C15ull;
2347 state = (state ^ (state >> 30)) * 0xBF58476D1CE4E5B9ull;
2348 state = (state ^ (state >> 27)) * 0x94D049BB133111EBull;
2349 state ^= high + 0x9E3779B97F4A7C15ull + (state << 6) + (state >> 2);
2350 state = (state ^ (state >> 30)) * 0xBF58476D1CE4E5B9ull;
2351 return static_cast<size_t>(state ^ (state >> 31));
2352 }
2353};
2354
2355/**
2356 * @brief std::format support for the 128 bit integer types.
2357 *
2358 * Accepts fill and alignment, a sign, a width and the d type. The other integer presentations that
2359 * `<format>` defines for a builtin - b, o, x and c - are not offered, because the conversion the
2360 * type provides is decimal.
2361 */
2362template <bool IsSigned> struct formatter<fp128::int128_base<IsSigned>, char>
2363{
2364 constexpr auto parse(basic_format_parse_context<char>& context)
2365 {
2366 auto it = context.begin();
2367 const auto end = context.end();
2368 if (it == end || *it == '}')
2369 return it;
2370
2371 const auto is_align = [](char c) { return c == '<' || c == '>' || c == '^'; };
2372 if (it + 1 != end && is_align(*(it + 1))) {
2373 fill = *it;
2374 align = *(it + 1);
2375 it += 2;
2376 } else if (is_align(*it)) {
2377 align = *it++;
2378 }
2379
2380 if (it != end && (*it == '+' || *it == '-' || *it == ' '))
2381 sign = *it++;
2382
2383 if (it != end && *it == '0') {
2384 zero_pad = true;
2385 ++it;
2386 }
2387
2388 while (it != end && *it >= '0' && *it <= '9')
2389 width = width * 10 + (*it++ - '0');
2390
2391 if (it != end && *it == 'd')
2392 ++it;
2393
2394 if (it != end && *it != '}')
2395 throw format_error("invalid format specification for a 128 bit integer");
2396 return it;
2397 }
2398
2399 template <typename FormatContext> auto format(const fp128::int128_base<IsSigned>& value, FormatContext& context) const
2400 {
2401 string text = static_cast<string>(value);
2402 if (sign != '-' && !text.empty() && text[0] != '-')
2403 text.insert(text.begin(), sign);
2404
2405 if (static_cast<int>(text.size()) < width) {
2406 const size_t padding = static_cast<size_t>(width) - text.size();
2407 if (zero_pad && align == 0) {
2408 const size_t offset = (!text.empty() && (text[0] == '-' || text[0] == '+' || text[0] == ' ')) ? 1u : 0u;
2409 text.insert(offset, padding, '0');
2410 } else if (align == '<') {
2411 text.append(padding, fill);
2412 } else if (align == '^') {
2413 text.insert(0, padding / 2, fill);
2414 text.append(padding - padding / 2, fill);
2415 } else {
2416 text.insert(0, padding, fill);
2417 }
2418 }
2419 return std::copy(text.begin(), text.end(), context.out());
2420 }
2421
2422 char fill = ' '; ///< Character the padding is made of.
2423 char align = 0; ///< One of < > ^, or zero when none was given.
2424 char sign = '-'; ///< One of + - space.
2425 bool zero_pad = false; ///< The 0 flag: pad with zeros after the sign.
2426 int width = 0; ///< Minimum field width.
2427};
2428} // namespace std
2429#endif // FP128_INT128_SHARED_H
128 bit integer class, signed or unsigned depending on the template parameter.
constexpr bool is_zero() const noexcept
constexpr int128_base operator~() const noexcept
Bitwise not (~).
static constexpr bool is_signed
constexpr bool operator>=(const T &rhs) const noexcept
Return true this object is larger or equal than the rhs.
constexpr int128_base & operator*=(T x) noexcept
Multiplies a value to this object.
int128_base & operator/=(const int128_base &rhs_in)
Divide this object by rhs.
constexpr int128_base(const int128_base &rhs) noexcept
Copy constructor.
constexpr bool operator==(const int128_base &rhs) const noexcept
Compare logical/bitwise equal.
friend int128_base operator/(const T &lhs, const int128_base &rhs)
Divides a scalar by an int128_base.
constexpr int128_base & operator^=(const int128_base &rhs) noexcept
Bitwise XOR=.
int128_base & operator/=(T x)
Divide this object by x.
friend constexpr int128_base operator+(int128_base lhs, const T &rhs) noexcept
Adds 2 values and returns the result.
constexpr int128_base(T x) noexcept
Constructor from any builtin integral type.
constexpr int128_base & square() noexcept
Squares this object in place.
constexpr bool operator==(const T &rhs) const noexcept
Compare logical/bitwise equal.
constexpr bool operator!() const noexcept
Logical not (!). Opposite of operator bool.
friend constexpr int128_base operator+(const T &lhs, const int128_base &rhs) noexcept
Adds a scalar and an int128_base, in that order.
constexpr int128_base & operator--() noexcept
Prefix – operation (–a)
static constexpr int128_base one() noexcept
Return an instance of int128_base with the value of 1.
constexpr int128_base() noexcept
Default constructor, creates an instance with a value of zero. Explicitly zeroing both QWORDs rather ...
constexpr int128_base & operator=(const T &rhs) noexcept
Assignment operator.
constexpr int128_base & operator-=(const T &rhs) noexcept
Subtract a value from this object like other builtin integer types, underflow wraps around silently.
constexpr int128_base operator++(int32_t) noexcept
Postfix ++ operation (a++)
friend constexpr int128_base operator&(int128_base lhs, const T &rhs) noexcept
Performs bitwise AND (&).
int128_base * ptr_type
Pointer type alias.
friend constexpr bool operator<(const T &lhs, const int128_base &rhs) noexcept
Returns true when a scalar is smaller than an int128_base.
constexpr bool operator>(const int128_base &rhs) const noexcept
Return true this object is larger than the rhs.
constexpr int128_base operator--(int32_t) noexcept
Postfix – operation (a–)
constexpr ~int128_base() noexcept=default
Destructor.
friend constexpr int128_base operator|(int128_base lhs, const T &rhs) noexcept
Performs bitwise OR (|).
int128_base type
Self type alias.
friend constexpr int128_base operator|(const T &lhs, const int128_base &rhs) noexcept
Performs bitwise OR of a scalar and an int128_base.
constexpr int128_base & operator&=(const int128_base &rhs) noexcept
Bitwise AND=.
constexpr int128_base & operator|=(const int128_base &rhs) noexcept
Bitwise OR=.
constexpr int128_base & operator=(int128_base &&rhs) noexcept
Move assignment operator Doesn't modify the right hand side object. Acts like a copy assignment opera...
constexpr int128_base(int128_base &&rhs) noexcept
Move constructor Doesn't modify the right hand side object. Acts like a copy constructor.
friend constexpr int128_base operator^(int128_base lhs, const T &rhs) noexcept
Performs bitwise XOR (^).
friend constexpr bool operator>=(const T &lhs, const int128_base &rhs) noexcept
Returns true when a scalar is larger or equal to an int128_base.
friend constexpr int128_base abs(const int128_base &x) noexcept
Calculates the absolute value of x. Only declared for the signed instantiation. An unqualified abs() ...
constexpr int128_base operator-() const noexcept
Unary -. Returns a copy of the object with sign inverted. Performs a 2's complement operation just li...
constexpr int128_base & operator&=(const T &rhs) noexcept
Bitwise AND=.
friend uint64_t log10(const int128_base &x)
Calculates Log base 10 of x: log10(x), rounded down to the nearest integer.
constexpr int128_base(uint64_t l, uint64_t h) noexcept
Constructor from the 2 int128_base elements, useful for creating special constants.
friend constexpr uint64_t log2(const int128_base &x)
constexpr int128_base & operator-=(const int128_base &rhs) noexcept
Subtract a value from this object like other builtin integer types, underflow wraps around silently.
friend constexpr int128_base operator*(const T &lhs, const int128_base &rhs) noexcept
Multiplies a scalar and an int128_base, in that order.
friend constexpr int128_base operator-(int128_base lhs, const T &rhs) noexcept
Subtracts 2 values and returns the result.
constexpr bool operator<(const int128_base &rhs) const noexcept
Return true if this object is small than the rhs.
friend constexpr int128_base operator&(const T &lhs, const int128_base &rhs) noexcept
Performs bitwise AND of a scalar and an int128_base.
constexpr int128_base & operator+=(const T &rhs) noexcept
Add a value to this object like other builtin integer types, overflow wraps around silently.
constexpr int128_base & operator<<=(int32_t shift) noexcept
Shift left this object.
int128_base & operator%=(const int128_base &rhs)
%= operator
friend constexpr int128_base operator-(const T &lhs, const int128_base &rhs) noexcept
Subtracts an int128_base from a scalar.
int128_base(const char *x) noexcept
Constructor from const char* (C string). Allows creating 128 bit values from a string....
constexpr bool operator<=(const int128_base &rhs) const noexcept
Return true this object is small or equal than the rhs.
friend int128_base operator%(int128_base lhs, const T &rhs)
Performs modulo and returns the result.
friend int128_base operator/(int128_base lhs, const T &rhs)
Divides 2 values and returns the result.
constexpr bool operator>=(const int128_base &rhs) const noexcept
Return true this object is larger or equal than the rhs.
constexpr int128_base & operator>>=(int32_t shift) noexcept
Shift right this object. The signed type shifts arithmetically, replicating the sign bit; the unsigne...
friend int128_base operator%(const T &lhs, const int128_base &rhs)
Performs modulo of a scalar by an int128_base.
friend constexpr int128_base pow(const int128_base &x, uint32_t y) noexcept
Calculates x to the power of y.
constexpr bool is_negative() const noexcept
constexpr bool is_int() const noexcept
Returns true if the value is an int (fraction is zero)
constexpr int128_base & operator*=(const int128_base &rhs) noexcept
Multiplies a value to this object.
friend constexpr bool operator==(const T &lhs, const int128_base &rhs) noexcept
Compares a scalar and an int128_base for equality.
constexpr int128_base(double x) noexcept
Constructor from the double type Underflow goes to zero. Overflow, NaN and +-INF go to the largest su...
friend constexpr int128_base operator>>(const T &lhs, const int128_base &rhs) noexcept
Shifts a scalar right by an int128_base shift count. The left operand is widened to int128_base first...
constexpr int32_t get_bit(uint32_t bit) const noexcept
get a specific bit within the 128 data
constexpr int128_base & operator++() noexcept
Prefix ++ operation (++a)
friend constexpr uint64_t lzcnt128(const int128_base &x) noexcept
Calculates the left zero count of value x.
constexpr bool operator!=(const T &rhs) const noexcept
Return true when objects are not equal. Can be used as logical XOR.
friend constexpr int128_base sqr(int128_base x) noexcept
Calculates the square of a value. i.e. x^2.
char * hex() const noexcept
Converts this object to a hex C string. The returned string is a statically thread-allocated buffer....
int128_base & ref_type
Reference type alias.
constexpr int128_base operator>>(int32_t shift) const noexcept
Performs right shift operation.
constexpr int128_base & operator|=(const T &rhs) noexcept
Bitwise OR=.
friend constexpr int128_base operator^(const T &lhs, const int128_base &rhs) noexcept
Performs bitwise XOR of a scalar and an int128_base.
friend uint64_t log(const int128_base &x)
Calculates the natural Log (base e) of x: log(x), rounded down to the nearest integer.
friend constexpr int128_base operator*(int128_base lhs, const T &rhs) noexcept
Multiplies 2 values and returns the result.
constexpr bool is_positive() const noexcept
Returns true if the value is positive (including zero) Always true for the unsigned type,...
friend constexpr bool operator!=(const T &lhs, const int128_base &rhs) noexcept
Compares a scalar and an int128_base for inequality.
constexpr int128_base & operator^=(const T &rhs) noexcept
Bitwise XOR=.
constexpr void get_components(uint64_t &l, uint64_t &h) const noexcept
Extracts the low and high QWORD.
constexpr int128_base operator+() const noexcept
Unary +. Returns a copy of the object.
constexpr bool operator>(const T &rhs) const noexcept
Return true this object is larger than the rhs.
int128_base & operator%=(T x)
%= operator
constexpr int128_base & operator+=(const int128_base &rhs) noexcept
Add a value to this object like other builtin integer types, overflow wraps around silently.
int128_base(const std::string &x) noexcept
Constructor from std::string. Allows creating very high precision values. Much slower than the other ...
constexpr bool operator!=(const int128_base &rhs) const noexcept
Return true when objects are not equal. Can be used as logical XOR.
constexpr int128_base operator<<(int32_t shift) const noexcept
Performs left shift operation.
friend constexpr bool operator<=(const T &lhs, const int128_base &rhs) noexcept
Returns true when a scalar is smaller or equal to an int128_base.
friend constexpr bool operator>(const T &lhs, const int128_base &rhs) noexcept
Returns true when a scalar is larger than an int128_base.
friend uint64_t sqrt(const int128_base &x) noexcept
Calculates the square root using Newton's method. Based on the book "Math toolkit for real time progr...
friend constexpr int128_base operator<<(const T &lhs, const int128_base &rhs) noexcept
Shifts a scalar left by an int128_base shift count.
constexpr bool operator<(const T &rhs) const noexcept
Return true if this object is small than the rhs.
char * to_string() const noexcept
Converts to a char* (slow) string holds all meaningful fraction bits.
constexpr bool operator<=(const T &rhs) const noexcept
Return true this object is small or equal than the rhs.
static constexpr int digits
Value bits, which excludes the sign bit for the signed type.
static FP128_SUPPRESS_DEPRECATED_BEGIN constexpr bool has_denorm_loss
static constexpr value_type epsilon() noexcept
static constexpr value_type infinity() noexcept
static constexpr float_denorm_style has_denorm
static constexpr value_type denorm_min() noexcept
static constexpr bool traps
Division by zero throws std::logic_error rather than producing a value.
static constexpr value_type quiet_NaN() noexcept
static FP128_SUPPRESS_DEPRECATED_END constexpr float_round_style round_style
static constexpr value_type min() noexcept
static constexpr bool is_modulo
Both types wrap around: +, - and * keep the low 128 bits of the exact result, which differs from it b...
static constexpr int digits10
Decimal digits that can be represented without change: floor(digits * log10(2)), which is 38 for both...
static constexpr value_type max() noexcept
static constexpr value_type round_error() noexcept
static constexpr value_type lowest() noexcept
static constexpr value_type signaling_NaN() noexcept
Shared definitions, intrinsics, and helper functions for 128-bit fixed-point arithmetic.
#define FP128_SUPPRESS_DEPRECATED_END
Closes the region opened by FP128_SUPPRESS_DEPRECATED_BEGIN.
#define FP128_SUPPRESS_DEPRECATED_BEGIN
Opens a region in which the use of a deprecated declaration is not reported.
#define FP128_ONE_SHIFT(x)
#define FP128_GET_BIT(x, n)
#define FP128_INLINE
#define FP128_FORCE_INLINE
Marks a function the compiler must inline rather than merely may.
#define FP128_INT_DIVIDE_BY_ZERO_EXCEPTION
#define FP128_ALIGN16
Everything the library provides.
constexpr uint32_t array_length(const T &a)
Calculates the element count of a C style array at build time Example: int a[5]; constexpr int len = ...
static bool div_64bit(uint64_t *q, uint64_t *r, const uint64_t *u, uint64_t v, int64_t m) noexcept
64 bit words unsigned divide function. Variation of the code from the book Hacker's Delight.
constexpr void twos_complement128(uint64_t &l, uint64_t &h) noexcept
converts a 128 integer to negative via 2's complement.
static bool div_128bit(uint64_t *q, uint64_t *r, const uint64_t *u, const uint64_t *v) noexcept
Divides an unsigned integer of up to 256 bits by a 128 bit one. Knuth algorithm D,...
static constexpr int32_t flt_frac_bits
Mantissa bit count of an IEEE 754 float.
std::istream & operator>>(std::istream &is, fixed_point128< I > &value)
Reads a fixed_point128 from a stream, the way the builtin arithmetic extractors do.
static errno_t strnlwr(char *dest, const char *src, size_t n) noexcept
Copy a string to lowercase, up to n characters.
static constexpr int32_t dbl_frac_bits
Mantissa bit count of an IEEE 754 double.
std::ostream & operator<<(std::ostream &os, const fixed_point128< I > &value)
Writes a fixed_point128 to a stream, honouring its width, fill and adjustment.
constexpr uint64_t shift_right128(uint64_t l, uint64_t h) noexcept
Right shift a 128 bit integer. When shift is a compile time constant, this function generates optimal...
constexpr uint64_t popcnt128(uint64_t l, uint64_t h) noexcept
Counts the number of 1 bits (population count) in a 128-bit unsigned integer.
STL namespace.
Bit level view of an IEEE 754 double-precision value.
constexpr uint64_t f() const noexcept
Mantissa (fraction) bits.
constexpr uint64_t s() const noexcept
Sign bit (0 = positive, 1 = negative).
static constexpr double make(uint64_t s, uint64_t e, uint64_t f) noexcept
Assembles a double out of its three fields.
constexpr uint64_t e() const noexcept
Biased exponent bits.
static constexpr float make(uint32_t s, uint32_t e, uint32_t f) noexcept
Assembles a float out of its three fields, see Double::make().
bool zero_pad
The 0 flag: pad with zeros after the sign.
char align
One of < > ^, or zero when none was given.
auto format(const fp128::int128_base< IsSigned > &value, FormatContext &context) const
constexpr auto parse(basic_format_parse_context< char > &context)
size_t operator()(const fp128::int128_base< IsSigned > &value) const noexcept