Coverage Report

Created: 2023-09-25 06:27

/src/abseil-cpp/absl/numeric/int128.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2017 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include "absl/numeric/int128.h"
16
17
#include <stddef.h>
18
19
#include <cassert>
20
#include <iomanip>
21
#include <ostream>  // NOLINT(readability/streams)
22
#include <sstream>
23
#include <string>
24
#include <type_traits>
25
26
#include "absl/base/optimization.h"
27
#include "absl/numeric/bits.h"
28
29
namespace absl {
30
ABSL_NAMESPACE_BEGIN
31
32
ABSL_DLL const uint128 kuint128max = MakeUint128(
33
    std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max());
34
35
namespace {
36
37
// Returns the 0-based position of the last set bit (i.e., most significant bit)
38
// in the given uint128. The argument is not 0.
39
//
40
// For example:
41
//   Given: 5 (decimal) == 101 (binary)
42
//   Returns: 2
43
0
inline ABSL_ATTRIBUTE_ALWAYS_INLINE int Fls128(uint128 n) {
44
0
  if (uint64_t hi = Uint128High64(n)) {
45
0
    ABSL_ASSUME(hi != 0);
46
0
    return 127 - countl_zero(hi);
47
0
  }
48
0
  const uint64_t low = Uint128Low64(n);
49
0
  ABSL_ASSUME(low != 0);
50
0
  return 63 - countl_zero(low);
51
0
}
52
53
// Long division/modulo for uint128 implemented using the shift-subtract
54
// division algorithm adapted from:
55
// https://stackoverflow.com/questions/5386377/division-without-using
56
inline void DivModImpl(uint128 dividend, uint128 divisor, uint128* quotient_ret,
57
0
                       uint128* remainder_ret) {
58
0
  assert(divisor != 0);
59
60
0
  if (divisor > dividend) {
61
0
    *quotient_ret = 0;
62
0
    *remainder_ret = dividend;
63
0
    return;
64
0
  }
65
66
0
  if (divisor == dividend) {
67
0
    *quotient_ret = 1;
68
0
    *remainder_ret = 0;
69
0
    return;
70
0
  }
71
72
0
  uint128 denominator = divisor;
73
0
  uint128 quotient = 0;
74
75
  // Left aligns the MSB of the denominator and the dividend.
76
0
  const int shift = Fls128(dividend) - Fls128(denominator);
77
0
  denominator <<= shift;
78
79
  // Uses shift-subtract algorithm to divide dividend by denominator. The
80
  // remainder will be left in dividend.
81
0
  for (int i = 0; i <= shift; ++i) {
82
0
    quotient <<= 1;
83
0
    if (dividend >= denominator) {
84
0
      dividend -= denominator;
85
0
      quotient |= 1;
86
0
    }
87
0
    denominator >>= 1;
88
0
  }
89
90
0
  *quotient_ret = quotient;
91
0
  *remainder_ret = dividend;
92
0
}
93
94
template <typename T>
95
0
uint128 MakeUint128FromFloat(T v) {
96
0
  static_assert(std::is_floating_point<T>::value, "");
97
98
  // Rounding behavior is towards zero, same as for built-in types.
99
100
  // Undefined behavior if v is NaN or cannot fit into uint128.
101
0
  assert(std::isfinite(v) && v > -1 &&
102
0
         (std::numeric_limits<T>::max_exponent <= 128 ||
103
0
          v < std::ldexp(static_cast<T>(1), 128)));
104
105
0
  if (v >= std::ldexp(static_cast<T>(1), 64)) {
106
0
    uint64_t hi = static_cast<uint64_t>(std::ldexp(v, -64));
107
0
    uint64_t lo = static_cast<uint64_t>(v - std::ldexp(static_cast<T>(hi), 64));
108
0
    return MakeUint128(hi, lo);
109
0
  }
110
111
0
  return MakeUint128(0, static_cast<uint64_t>(v));
112
0
}
Unexecuted instantiation: int128.cc:absl::uint128 absl::(anonymous namespace)::MakeUint128FromFloat<float>(float)
Unexecuted instantiation: int128.cc:absl::uint128 absl::(anonymous namespace)::MakeUint128FromFloat<double>(double)
Unexecuted instantiation: int128.cc:absl::uint128 absl::(anonymous namespace)::MakeUint128FromFloat<long double>(long double)
113
114
#if defined(__clang__) && (__clang_major__ < 9) && !defined(__SSE3__)
115
// Workaround for clang bug: https://bugs.llvm.org/show_bug.cgi?id=38289
116
// Casting from long double to uint64_t is miscompiled and drops bits.
117
// It is more work, so only use when we need the workaround.
118
uint128 MakeUint128FromFloat(long double v) {
119
  // Go 50 bits at a time, that fits in a double
120
  static_assert(std::numeric_limits<double>::digits >= 50, "");
121
  static_assert(std::numeric_limits<long double>::digits <= 150, "");
122
  // Undefined behavior if v is not finite or cannot fit into uint128.
123
  assert(std::isfinite(v) && v > -1 && v < std::ldexp(1.0L, 128));
124
125
  v = std::ldexp(v, -100);
126
  uint64_t w0 = static_cast<uint64_t>(static_cast<double>(std::trunc(v)));
127
  v = std::ldexp(v - static_cast<double>(w0), 50);
128
  uint64_t w1 = static_cast<uint64_t>(static_cast<double>(std::trunc(v)));
129
  v = std::ldexp(v - static_cast<double>(w1), 50);
130
  uint64_t w2 = static_cast<uint64_t>(static_cast<double>(std::trunc(v)));
131
  return (static_cast<uint128>(w0) << 100) | (static_cast<uint128>(w1) << 50) |
132
         static_cast<uint128>(w2);
133
}
134
#endif  // __clang__ && (__clang_major__ < 9) && !__SSE3__
135
}  // namespace
136
137
0
uint128::uint128(float v) : uint128(MakeUint128FromFloat(v)) {}
138
0
uint128::uint128(double v) : uint128(MakeUint128FromFloat(v)) {}
139
0
uint128::uint128(long double v) : uint128(MakeUint128FromFloat(v)) {}
140
141
#if !defined(ABSL_HAVE_INTRINSIC_INT128)
142
uint128 operator/(uint128 lhs, uint128 rhs) {
143
  uint128 quotient = 0;
144
  uint128 remainder = 0;
145
  DivModImpl(lhs, rhs, &quotient, &remainder);
146
  return quotient;
147
}
148
149
uint128 operator%(uint128 lhs, uint128 rhs) {
150
  uint128 quotient = 0;
151
  uint128 remainder = 0;
152
  DivModImpl(lhs, rhs, &quotient, &remainder);
153
  return remainder;
154
}
155
#endif  // !defined(ABSL_HAVE_INTRINSIC_INT128)
156
157
namespace {
158
159
0
std::string Uint128ToFormattedString(uint128 v, std::ios_base::fmtflags flags) {
160
  // Select a divisor which is the largest power of the base < 2^64.
161
0
  uint128 div;
162
0
  int div_base_log;
163
0
  switch (flags & std::ios::basefield) {
164
0
    case std::ios::hex:
165
0
      div = 0x1000000000000000;  // 16^15
166
0
      div_base_log = 15;
167
0
      break;
168
0
    case std::ios::oct:
169
0
      div = 01000000000000000000000;  // 8^21
170
0
      div_base_log = 21;
171
0
      break;
172
0
    default:  // std::ios::dec
173
0
      div = 10000000000000000000u;  // 10^19
174
0
      div_base_log = 19;
175
0
      break;
176
0
  }
177
178
  // Now piece together the uint128 representation from three chunks of the
179
  // original value, each less than "div" and therefore representable as a
180
  // uint64_t.
181
0
  std::ostringstream os;
182
0
  std::ios_base::fmtflags copy_mask =
183
0
      std::ios::basefield | std::ios::showbase | std::ios::uppercase;
184
0
  os.setf(flags & copy_mask, copy_mask);
185
0
  uint128 high = v;
186
0
  uint128 low;
187
0
  DivModImpl(high, div, &high, &low);
188
0
  uint128 mid;
189
0
  DivModImpl(high, div, &high, &mid);
190
0
  if (Uint128Low64(high) != 0) {
191
0
    os << Uint128Low64(high);
192
0
    os << std::noshowbase << std::setfill('0') << std::setw(div_base_log);
193
0
    os << Uint128Low64(mid);
194
0
    os << std::setw(div_base_log);
195
0
  } else if (Uint128Low64(mid) != 0) {
196
0
    os << Uint128Low64(mid);
197
0
    os << std::noshowbase << std::setfill('0') << std::setw(div_base_log);
198
0
  }
199
0
  os << Uint128Low64(low);
200
0
  return os.str();
201
0
}
202
203
}  // namespace
204
205
0
std::string uint128::ToString() const {
206
0
  return Uint128ToFormattedString(*this, std::ios_base::dec);
207
0
}
208
209
0
std::ostream& operator<<(std::ostream& os, uint128 v) {
210
0
  std::ios_base::fmtflags flags = os.flags();
211
0
  std::string rep = Uint128ToFormattedString(v, flags);
212
213
  // Add the requisite padding.
214
0
  std::streamsize width = os.width(0);
215
0
  if (static_cast<size_t>(width) > rep.size()) {
216
0
    const size_t count = static_cast<size_t>(width) - rep.size();
217
0
    std::ios::fmtflags adjustfield = flags & std::ios::adjustfield;
218
0
    if (adjustfield == std::ios::left) {
219
0
      rep.append(count, os.fill());
220
0
    } else if (adjustfield == std::ios::internal &&
221
0
               (flags & std::ios::showbase) &&
222
0
               (flags & std::ios::basefield) == std::ios::hex && v != 0) {
223
0
      rep.insert(size_t{2}, count, os.fill());
224
0
    } else {
225
0
      rep.insert(size_t{0}, count, os.fill());
226
0
    }
227
0
  }
228
229
0
  return os << rep;
230
0
}
231
232
namespace {
233
234
0
uint128 UnsignedAbsoluteValue(int128 v) {
235
  // Cast to uint128 before possibly negating because -Int128Min() is undefined.
236
0
  return Int128High64(v) < 0 ? -uint128(v) : uint128(v);
237
0
}
238
239
}  // namespace
240
241
#if !defined(ABSL_HAVE_INTRINSIC_INT128)
242
namespace {
243
244
template <typename T>
245
int128 MakeInt128FromFloat(T v) {
246
  // Conversion when v is NaN or cannot fit into int128 would be undefined
247
  // behavior if using an intrinsic 128-bit integer.
248
  assert(std::isfinite(v) && (std::numeric_limits<T>::max_exponent <= 127 ||
249
                              (v >= -std::ldexp(static_cast<T>(1), 127) &&
250
                               v < std::ldexp(static_cast<T>(1), 127))));
251
252
  // We must convert the absolute value and then negate as needed, because
253
  // floating point types are typically sign-magnitude. Otherwise, the
254
  // difference between the high and low 64 bits when interpreted as two's
255
  // complement overwhelms the precision of the mantissa.
256
  uint128 result = v < 0 ? -MakeUint128FromFloat(-v) : MakeUint128FromFloat(v);
257
  return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(result)),
258
                    Uint128Low64(result));
259
}
260
261
}  // namespace
262
263
int128::int128(float v) : int128(MakeInt128FromFloat(v)) {}
264
int128::int128(double v) : int128(MakeInt128FromFloat(v)) {}
265
int128::int128(long double v) : int128(MakeInt128FromFloat(v)) {}
266
267
int128 operator/(int128 lhs, int128 rhs) {
268
  assert(lhs != Int128Min() || rhs != -1);  // UB on two's complement.
269
270
  uint128 quotient = 0;
271
  uint128 remainder = 0;
272
  DivModImpl(UnsignedAbsoluteValue(lhs), UnsignedAbsoluteValue(rhs),
273
             &quotient, &remainder);
274
  if ((Int128High64(lhs) < 0) != (Int128High64(rhs) < 0)) quotient = -quotient;
275
  return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(quotient)),
276
                    Uint128Low64(quotient));
277
}
278
279
int128 operator%(int128 lhs, int128 rhs) {
280
  assert(lhs != Int128Min() || rhs != -1);  // UB on two's complement.
281
282
  uint128 quotient = 0;
283
  uint128 remainder = 0;
284
  DivModImpl(UnsignedAbsoluteValue(lhs), UnsignedAbsoluteValue(rhs),
285
             &quotient, &remainder);
286
  if (Int128High64(lhs) < 0) remainder = -remainder;
287
  return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(remainder)),
288
                    Uint128Low64(remainder));
289
}
290
#endif  // ABSL_HAVE_INTRINSIC_INT128
291
292
0
std::string int128::ToString() const {
293
0
  std::string rep;
294
0
  if (Int128High64(*this) < 0) rep = "-";
295
0
  rep.append(Uint128ToFormattedString(UnsignedAbsoluteValue(*this),
296
0
                                      std::ios_base::dec));
297
0
  return rep;
298
0
}
299
300
0
std::ostream& operator<<(std::ostream& os, int128 v) {
301
0
  std::ios_base::fmtflags flags = os.flags();
302
0
  std::string rep;
303
304
  // Add the sign if needed.
305
0
  bool print_as_decimal =
306
0
      (flags & std::ios::basefield) == std::ios::dec ||
307
0
      (flags & std::ios::basefield) == std::ios_base::fmtflags();
308
0
  if (print_as_decimal) {
309
0
    if (Int128High64(v) < 0) {
310
0
      rep = "-";
311
0
    } else if (flags & std::ios::showpos) {
312
0
      rep = "+";
313
0
    }
314
0
  }
315
316
0
  rep.append(Uint128ToFormattedString(
317
0
      print_as_decimal ? UnsignedAbsoluteValue(v) : uint128(v), os.flags()));
318
319
  // Add the requisite padding.
320
0
  std::streamsize width = os.width(0);
321
0
  if (static_cast<size_t>(width) > rep.size()) {
322
0
    const size_t count = static_cast<size_t>(width) - rep.size();
323
0
    switch (flags & std::ios::adjustfield) {
324
0
      case std::ios::left:
325
0
        rep.append(count, os.fill());
326
0
        break;
327
0
      case std::ios::internal:
328
0
        if (print_as_decimal && (rep[0] == '+' || rep[0] == '-')) {
329
0
          rep.insert(size_t{1}, count, os.fill());
330
0
        } else if ((flags & std::ios::basefield) == std::ios::hex &&
331
0
                   (flags & std::ios::showbase) && v != 0) {
332
0
          rep.insert(size_t{2}, count, os.fill());
333
0
        } else {
334
0
          rep.insert(size_t{0}, count, os.fill());
335
0
        }
336
0
        break;
337
0
      default:  // std::ios::right
338
0
        rep.insert(size_t{0}, count, os.fill());
339
0
        break;
340
0
    }
341
0
  }
342
343
0
  return os << rep;
344
0
}
345
346
ABSL_NAMESPACE_END
347
}  // namespace absl
348
349
#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
350
namespace std {
351
constexpr bool numeric_limits<absl::uint128>::is_specialized;
352
constexpr bool numeric_limits<absl::uint128>::is_signed;
353
constexpr bool numeric_limits<absl::uint128>::is_integer;
354
constexpr bool numeric_limits<absl::uint128>::is_exact;
355
constexpr bool numeric_limits<absl::uint128>::has_infinity;
356
constexpr bool numeric_limits<absl::uint128>::has_quiet_NaN;
357
constexpr bool numeric_limits<absl::uint128>::has_signaling_NaN;
358
constexpr float_denorm_style numeric_limits<absl::uint128>::has_denorm;
359
constexpr bool numeric_limits<absl::uint128>::has_denorm_loss;
360
constexpr float_round_style numeric_limits<absl::uint128>::round_style;
361
constexpr bool numeric_limits<absl::uint128>::is_iec559;
362
constexpr bool numeric_limits<absl::uint128>::is_bounded;
363
constexpr bool numeric_limits<absl::uint128>::is_modulo;
364
constexpr int numeric_limits<absl::uint128>::digits;
365
constexpr int numeric_limits<absl::uint128>::digits10;
366
constexpr int numeric_limits<absl::uint128>::max_digits10;
367
constexpr int numeric_limits<absl::uint128>::radix;
368
constexpr int numeric_limits<absl::uint128>::min_exponent;
369
constexpr int numeric_limits<absl::uint128>::min_exponent10;
370
constexpr int numeric_limits<absl::uint128>::max_exponent;
371
constexpr int numeric_limits<absl::uint128>::max_exponent10;
372
constexpr bool numeric_limits<absl::uint128>::traps;
373
constexpr bool numeric_limits<absl::uint128>::tinyness_before;
374
375
constexpr bool numeric_limits<absl::int128>::is_specialized;
376
constexpr bool numeric_limits<absl::int128>::is_signed;
377
constexpr bool numeric_limits<absl::int128>::is_integer;
378
constexpr bool numeric_limits<absl::int128>::is_exact;
379
constexpr bool numeric_limits<absl::int128>::has_infinity;
380
constexpr bool numeric_limits<absl::int128>::has_quiet_NaN;
381
constexpr bool numeric_limits<absl::int128>::has_signaling_NaN;
382
constexpr float_denorm_style numeric_limits<absl::int128>::has_denorm;
383
constexpr bool numeric_limits<absl::int128>::has_denorm_loss;
384
constexpr float_round_style numeric_limits<absl::int128>::round_style;
385
constexpr bool numeric_limits<absl::int128>::is_iec559;
386
constexpr bool numeric_limits<absl::int128>::is_bounded;
387
constexpr bool numeric_limits<absl::int128>::is_modulo;
388
constexpr int numeric_limits<absl::int128>::digits;
389
constexpr int numeric_limits<absl::int128>::digits10;
390
constexpr int numeric_limits<absl::int128>::max_digits10;
391
constexpr int numeric_limits<absl::int128>::radix;
392
constexpr int numeric_limits<absl::int128>::min_exponent;
393
constexpr int numeric_limits<absl::int128>::min_exponent10;
394
constexpr int numeric_limits<absl::int128>::max_exponent;
395
constexpr int numeric_limits<absl::int128>::max_exponent10;
396
constexpr bool numeric_limits<absl::int128>::traps;
397
constexpr bool numeric_limits<absl::int128>::tinyness_before;
398
}  // namespace std
399
#endif