Coverage Report

Created: 2026-07-16 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgis/deps/ryu/d2s.c
Line
Count
Source
1
// Copyright 2018 Ulf Adams
2
//
3
// The contents of this file may be used under the terms of the Apache License,
4
// Version 2.0.
5
//
6
//    (See accompanying file LICENSE-Apache or copy at
7
//     http://www.apache.org/licenses/LICENSE-2.0)
8
//
9
// Alternatively, the contents of this file may be used under the terms of
10
// the Boost Software License, Version 1.0.
11
//    (See accompanying file LICENSE-Boost or copy at
12
//     https://www.boost.org/LICENSE_1_0.txt)
13
//
14
// Unless required by applicable law or agreed to in writing, this software
15
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
// KIND, either express or implied.
17
18
// Runtime compiler options:
19
// -DRYU_DEBUG Generate verbose debugging output to stdout.
20
//
21
// -DRYU_ONLY_64_BIT_OPS Avoid using uint128_t or 64-bit intrinsics. Slower,
22
//     depending on your compiler.
23
//
24
// -DRYU_OPTIMIZE_SIZE Use smaller lookup tables. Instead of storing every
25
//     required power of 5, only store every 26th entry, and compute
26
//     intermediate values with a multiplication. This reduces the lookup table
27
//     size by about 10x (only one case, and only double) at the cost of some
28
//     performance. Currently requires MSVC intrinsics.
29
30
#include "ryu/ryu.h"
31
32
#include <assert.h>
33
#include <stdbool.h>
34
#include <stdint.h>
35
#include <stdlib.h>
36
#include <string.h>
37
38
#ifdef RYU_DEBUG
39
#include <inttypes.h>
40
#include <stdio.h>
41
#endif
42
43
#include "ryu/common.h"
44
#include "ryu/digit_table.h"
45
#include "ryu/d2s_intrinsics.h"
46
47
// Include either the small or the full lookup tables depending on the mode.
48
#if defined(RYU_OPTIMIZE_SIZE)
49
#include "ryu/d2s_small_table.h"
50
#else
51
#include "ryu/d2s_full_table.h"
52
#endif
53
54
0
#define DOUBLE_MANTISSA_BITS 52
55
0
#define DOUBLE_EXPONENT_BITS 11
56
0
#define DOUBLE_BIAS 1023
57
58
// We need a 64x128-bit multiplication and a subsequent 128-bit shift.
59
// Multiplication:
60
//   The 64-bit factor is variable and passed in, the 128-bit factor comes
61
//   from a lookup table. We know that the 64-bit factor only has 55
62
//   significant bits (i.e., the 9 topmost bits are zeros). The 128-bit
63
//   factor only has 124 significant bits (i.e., the 4 topmost bits are
64
//   zeros).
65
// Shift:
66
//   In principle, the multiplication result requires 55 + 124 = 179 bits to
67
//   represent. However, we then shift this value to the right by j, which is
68
//   at least j >= 115, so the result is guaranteed to fit into 179 - 115 = 64
69
//   bits. This means that we only need the topmost 64 significant bits of
70
//   the 64x128-bit multiplication.
71
//
72
// There are several ways to do this:
73
// 1. Best case: the compiler exposes a 128-bit type.
74
//    We perform two 64x64-bit multiplications, add the higher 64 bits of the
75
//    lower result to the higher result, and shift by j - 64 bits.
76
//
77
//    We explicitly cast from 64-bit to 128-bit, so the compiler can tell
78
//    that these are only 64-bit inputs, and can map these to the best
79
//    possible sequence of assembly instructions.
80
//    x64 machines happen to have matching assembly instructions for
81
//    64x64-bit multiplications and 128-bit shifts.
82
//
83
// 2. Second best case: the compiler exposes intrinsics for the x64 assembly
84
//    instructions mentioned in 1.
85
//
86
// 3. We only have 64x64 bit instructions that return the lower 64 bits of
87
//    the result, i.e., we have to use plain C.
88
//    Our inputs are less than the full width, so we have three options:
89
//    a. Ignore this fact and just implement the intrinsics manually.
90
//    b. Split both into 31-bit pieces, which guarantees no internal overflow,
91
//       but requires extra work upfront (unless we change the lookup table).
92
//    c. Split only the first factor into 31-bit pieces, which also guarantees
93
//       no internal overflow, but requires extra work since the intermediate
94
//       results are not perfectly aligned.
95
#if defined(HAS_UINT128)
96
97
// Best case: use 128-bit type.
98
0
static inline uint64_t mulShift(const uint64_t m, const uint64_t* const mul, const int32_t j) {
99
0
  const uint128_t b0 = ((uint128_t) m) * mul[0];
100
0
  const uint128_t b2 = ((uint128_t) m) * mul[1];
101
0
  return (uint64_t) (((b0 >> 64) + b2) >> (j - 64));
102
0
}
103
104
static inline uint64_t mulShiftAll(const uint64_t m, const uint64_t* const mul, const int32_t j,
105
0
  uint64_t* const vp, uint64_t* const vm, const uint32_t mmShift) {
106
//  m <<= 2;
107
//  uint128_t b0 = ((uint128_t) m) * mul[0]; // 0
108
//  uint128_t b2 = ((uint128_t) m) * mul[1]; // 64
109
//
110
//  uint128_t hi = (b0 >> 64) + b2;
111
//  uint128_t lo = b0 & 0xffffffffffffffffull;
112
//  uint128_t factor = (((uint128_t) mul[1]) << 64) + mul[0];
113
//  uint128_t vpLo = lo + (factor << 1);
114
//  *vp = (uint64_t) ((hi + (vpLo >> 64)) >> (j - 64));
115
//  uint128_t vmLo = lo - (factor << mmShift);
116
//  *vm = (uint64_t) ((hi + (vmLo >> 64) - (((uint128_t) 1ull) << 64)) >> (j - 64));
117
//  return (uint64_t) (hi >> (j - 64));
118
0
  *vp = mulShift(4 * m + 2, mul, j);
119
0
  *vm = mulShift(4 * m - 1 - mmShift, mul, j);
120
0
  return mulShift(4 * m, mul, j);
121
0
}
122
123
#elif defined(HAS_64_BIT_INTRINSICS)
124
125
static inline uint64_t mulShift(const uint64_t m, const uint64_t* const mul, const int32_t j) {
126
  // m is maximum 55 bits
127
  uint64_t high1;                                   // 128
128
  const uint64_t low1 = umul128(m, mul[1], &high1); // 64
129
  uint64_t high0;                                   // 64
130
  umul128(m, mul[0], &high0);                       // 0
131
  const uint64_t sum = high0 + low1;
132
  if (sum < high0) {
133
    ++high1; // overflow into high1
134
  }
135
  return shiftright128(sum, high1, j - 64);
136
}
137
138
static inline uint64_t mulShiftAll(const uint64_t m, const uint64_t* const mul, const int32_t j,
139
  uint64_t* const vp, uint64_t* const vm, const uint32_t mmShift) {
140
  *vp = mulShift(4 * m + 2, mul, j);
141
  *vm = mulShift(4 * m - 1 - mmShift, mul, j);
142
  return mulShift(4 * m, mul, j);
143
}
144
145
#else // !defined(HAS_UINT128) && !defined(HAS_64_BIT_INTRINSICS)
146
147
static inline uint64_t mulShiftAll(uint64_t m, const uint64_t* const mul, const int32_t j,
148
  uint64_t* const vp, uint64_t* const vm, const uint32_t mmShift) {
149
  m <<= 1;
150
  // m is maximum 55 bits
151
  uint64_t tmp;
152
  const uint64_t lo = umul128(m, mul[0], &tmp);
153
  uint64_t hi;
154
  const uint64_t mid = tmp + umul128(m, mul[1], &hi);
155
  hi += mid < tmp; // overflow into hi
156
157
  const uint64_t lo2 = lo + mul[0];
158
  const uint64_t mid2 = mid + mul[1] + (lo2 < lo);
159
  const uint64_t hi2 = hi + (mid2 < mid);
160
  *vp = shiftright128(mid2, hi2, (uint32_t) (j - 64 - 1));
161
162
  if (mmShift == 1) {
163
    const uint64_t lo3 = lo - mul[0];
164
    const uint64_t mid3 = mid - mul[1] - (lo3 > lo);
165
    const uint64_t hi3 = hi - (mid3 > mid);
166
    *vm = shiftright128(mid3, hi3, (uint32_t) (j - 64 - 1));
167
  } else {
168
    const uint64_t lo3 = lo + lo;
169
    const uint64_t mid3 = mid + mid + (lo3 < lo);
170
    const uint64_t hi3 = hi + hi + (mid3 < mid);
171
    const uint64_t lo4 = lo3 - mul[0];
172
    const uint64_t mid4 = mid3 - mul[1] - (lo4 > lo3);
173
    const uint64_t hi4 = hi3 - (mid4 > mid3);
174
    *vm = shiftright128(mid4, hi4, (uint32_t) (j - 64));
175
  }
176
177
  return shiftright128(mid, hi, (uint32_t) (j - 64 - 1));
178
}
179
180
#endif // HAS_64_BIT_INTRINSICS
181
182
0
static inline uint32_t decimalLength17(const uint64_t v) {
183
  // This is slightly faster than a loop.
184
  // The average output length is 16.38 digits, so we check high-to-low.
185
  // Function precondition: v is not an 18, 19, or 20-digit number.
186
  // (17 digits are sufficient for round-tripping.)
187
0
  assert(v < 100000000000000000L);
188
0
  if (v >= 10000000000000000L) { return 17; }
189
0
  if (v >= 1000000000000000L) { return 16; }
190
0
  if (v >= 100000000000000L) { return 15; }
191
0
  if (v >= 10000000000000L) { return 14; }
192
0
  if (v >= 1000000000000L) { return 13; }
193
0
  if (v >= 100000000000L) { return 12; }
194
0
  if (v >= 10000000000L) { return 11; }
195
0
  if (v >= 1000000000L) { return 10; }
196
0
  if (v >= 100000000L) { return 9; }
197
0
  if (v >= 10000000L) { return 8; }
198
0
  if (v >= 1000000L) { return 7; }
199
0
  if (v >= 100000L) { return 6; }
200
0
  if (v >= 10000L) { return 5; }
201
0
  if (v >= 1000L) { return 4; }
202
0
  if (v >= 100L) { return 3; }
203
0
  if (v >= 10L) { return 2; }
204
0
  return 1;
205
0
}
206
207
// A floating decimal representing m * 10^e.
208
typedef struct floating_decimal_64 {
209
  uint64_t mantissa;
210
  // Decimal exponent's range is -324 to 308
211
  // inclusive, and can fit in a short if needed.
212
  int32_t exponent;
213
} floating_decimal_64;
214
215
0
static inline floating_decimal_64 d2d(const uint64_t ieeeMantissa, const uint32_t ieeeExponent) {
216
0
  int32_t e2;
217
0
  uint64_t m2;
218
0
  if (ieeeExponent == 0) {
219
    // We subtract 2 so that the bounds computation has 2 additional bits.
220
0
    e2 = 1 - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2;
221
0
    m2 = ieeeMantissa;
222
0
  } else {
223
0
    e2 = (int32_t) ieeeExponent - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2;
224
0
    m2 = (1ull << DOUBLE_MANTISSA_BITS) | ieeeMantissa;
225
0
  }
226
0
  const bool even = (m2 & 1) == 0;
227
0
  const bool acceptBounds = even;
228
229
#ifdef RYU_DEBUG
230
  printf("-> %" PRIu64 " * 2^%d\n", m2, e2 + 2);
231
#endif
232
233
  // Step 2: Determine the interval of valid decimal representations.
234
0
  const uint64_t mv = 4 * m2;
235
  // Implicit bool -> int conversion. True is 1, false is 0.
236
0
  const uint32_t mmShift = ieeeMantissa != 0 || ieeeExponent <= 1;
237
  // We would compute mp and mm like this:
238
  // uint64_t mp = 4 * m2 + 2;
239
  // uint64_t mm = mv - 1 - mmShift;
240
241
  // Step 3: Convert to a decimal power base using 128-bit arithmetic.
242
0
  uint64_t vr, vp, vm;
243
0
  int32_t e10;
244
0
  bool vmIsTrailingZeros = false;
245
0
  bool vrIsTrailingZeros = false;
246
0
  if (e2 >= 0) {
247
    // I tried special-casing q == 0, but there was no effect on performance.
248
    // This expression is slightly faster than max(0, log10Pow2(e2) - 1).
249
0
    const uint32_t q = log10Pow2(e2) - (e2 > 3);
250
0
    e10 = (int32_t) q;
251
0
    const int32_t k = DOUBLE_POW5_INV_BITCOUNT + pow5bits((int32_t) q) - 1;
252
0
    const int32_t i = -e2 + (int32_t) q + k;
253
#if defined(RYU_OPTIMIZE_SIZE)
254
    uint64_t pow5[2];
255
    double_computeInvPow5(q, pow5);
256
    vr = mulShiftAll(m2, pow5, i, &vp, &vm, mmShift);
257
#else
258
0
    vr = mulShiftAll(m2, DOUBLE_POW5_INV_SPLIT[q], i, &vp, &vm, mmShift);
259
0
#endif
260
#ifdef RYU_DEBUG
261
    printf("%" PRIu64 " * 2^%d / 10^%u\n", mv, e2, q);
262
    printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
263
#endif
264
0
    if (q <= 21) {
265
      // This should use q <= 22, but I think 21 is also safe. Smaller values
266
      // may still be safe, but it's more difficult to reason about them.
267
      // Only one of mp, mv, and mm can be a multiple of 5, if any.
268
0
      const uint32_t mvMod5 = ((uint32_t) mv) - 5 * ((uint32_t) div5(mv));
269
0
      if (mvMod5 == 0) {
270
0
        vrIsTrailingZeros = multipleOfPowerOf5(mv, q);
271
0
      } else if (acceptBounds) {
272
        // Same as min(e2 + (~mm & 1), pow5Factor(mm)) >= q
273
        // <=> e2 + (~mm & 1) >= q && pow5Factor(mm) >= q
274
        // <=> true && pow5Factor(mm) >= q, since e2 >= q.
275
0
        vmIsTrailingZeros = multipleOfPowerOf5(mv - 1 - mmShift, q);
276
0
      } else {
277
        // Same as min(e2 + 1, pow5Factor(mp)) >= q.
278
0
        vp -= multipleOfPowerOf5(mv + 2, q);
279
0
      }
280
0
    }
281
0
  } else {
282
    // This expression is slightly faster than max(0, log10Pow5(-e2) - 1).
283
0
    const uint32_t q = log10Pow5(-e2) - (-e2 > 1);
284
0
    e10 = (int32_t) q + e2;
285
0
    const int32_t i = -e2 - (int32_t) q;
286
0
    const int32_t k = pow5bits(i) - DOUBLE_POW5_BITCOUNT;
287
0
    const int32_t j = (int32_t) q - k;
288
#if defined(RYU_OPTIMIZE_SIZE)
289
    uint64_t pow5[2];
290
    double_computePow5(i, pow5);
291
    vr = mulShiftAll(m2, pow5, j, &vp, &vm, mmShift);
292
#else
293
0
    vr = mulShiftAll(m2, DOUBLE_POW5_SPLIT[i], j, &vp, &vm, mmShift);
294
0
#endif
295
#ifdef RYU_DEBUG
296
    printf("%" PRIu64 " * 5^%d / 10^%u\n", mv, -e2, q);
297
    printf("%u %d %d %d\n", q, i, k, j);
298
    printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
299
#endif
300
0
    if (q <= 1) {
301
      // {vr,vp,vm} is trailing zeros if {mv,mp,mm} has at least q trailing 0 bits.
302
      // mv = 4 * m2, so it always has at least two trailing 0 bits.
303
0
      vrIsTrailingZeros = true;
304
0
      if (acceptBounds) {
305
        // mm = mv - 1 - mmShift, so it has 1 trailing 0 bit iff mmShift == 1.
306
0
        vmIsTrailingZeros = mmShift == 1;
307
0
      } else {
308
        // mp = mv + 2, so it always has at least one trailing 0 bit.
309
0
        --vp;
310
0
      }
311
0
    } else if (q < 63) { // TODO(ulfjack): Use a tighter bound here.
312
      // We want to know if the full product has at least q trailing zeros.
313
      // We need to compute min(p2(mv), p5(mv) - e2) >= q
314
      // <=> p2(mv) >= q && p5(mv) - e2 >= q
315
      // <=> p2(mv) >= q (because -e2 >= q)
316
0
      vrIsTrailingZeros = multipleOfPowerOf2(mv, q);
317
#ifdef RYU_DEBUG
318
      printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
319
#endif
320
0
    }
321
0
  }
322
#ifdef RYU_DEBUG
323
  printf("e10=%d\n", e10);
324
  printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
325
  printf("vm is trailing zeros=%s\n", vmIsTrailingZeros ? "true" : "false");
326
  printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
327
#endif
328
329
  // Step 4: Find the shortest decimal representation in the interval of valid representations.
330
0
  int32_t removed = 0;
331
0
  uint8_t lastRemovedDigit = 0;
332
0
  uint64_t output;
333
  // On average, we remove ~2 digits.
334
0
  if (vmIsTrailingZeros || vrIsTrailingZeros) {
335
    // General case, which happens rarely (~0.7%).
336
0
    for (;;) {
337
0
      const uint64_t vpDiv10 = div10(vp);
338
0
      const uint64_t vmDiv10 = div10(vm);
339
0
      if (vpDiv10 <= vmDiv10) {
340
0
        break;
341
0
      }
342
0
      const uint32_t vmMod10 = ((uint32_t) vm) - 10 * ((uint32_t) vmDiv10);
343
0
      const uint64_t vrDiv10 = div10(vr);
344
0
      const uint32_t vrMod10 = ((uint32_t) vr) - 10 * ((uint32_t) vrDiv10);
345
0
      vmIsTrailingZeros &= vmMod10 == 0;
346
0
      vrIsTrailingZeros &= lastRemovedDigit == 0;
347
0
      lastRemovedDigit = (uint8_t) vrMod10;
348
0
      vr = vrDiv10;
349
0
      vp = vpDiv10;
350
0
      vm = vmDiv10;
351
0
      ++removed;
352
0
    }
353
#ifdef RYU_DEBUG
354
    printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
355
    printf("d-10=%s\n", vmIsTrailingZeros ? "true" : "false");
356
#endif
357
0
    if (vmIsTrailingZeros) {
358
0
      for (;;) {
359
0
        const uint64_t vmDiv10 = div10(vm);
360
0
        const uint32_t vmMod10 = ((uint32_t) vm) - 10 * ((uint32_t) vmDiv10);
361
0
        if (vmMod10 != 0) {
362
0
          break;
363
0
        }
364
0
        const uint64_t vpDiv10 = div10(vp);
365
0
        const uint64_t vrDiv10 = div10(vr);
366
0
        const uint32_t vrMod10 = ((uint32_t) vr) - 10 * ((uint32_t) vrDiv10);
367
0
        vrIsTrailingZeros &= lastRemovedDigit == 0;
368
0
        lastRemovedDigit = (uint8_t) vrMod10;
369
0
        vr = vrDiv10;
370
0
        vp = vpDiv10;
371
0
        vm = vmDiv10;
372
0
        ++removed;
373
0
      }
374
0
    }
375
#ifdef RYU_DEBUG
376
    printf("%" PRIu64 " %d\n", vr, lastRemovedDigit);
377
    printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
378
#endif
379
0
    if (vrIsTrailingZeros && lastRemovedDigit == 5 && vr % 2 == 0) {
380
      // Round even if the exact number is .....50..0.
381
0
      lastRemovedDigit = 4;
382
0
    }
383
    // We need to take vr + 1 if vr is outside bounds or we need to round up.
384
0
    output = vr + ((vr == vm && (!acceptBounds || !vmIsTrailingZeros)) || lastRemovedDigit >= 5);
385
0
  } else {
386
    // Specialized for the common case (~99.3%). Percentages below are relative to this.
387
0
    bool roundUp = false;
388
0
    const uint64_t vpDiv100 = div100(vp);
389
0
    const uint64_t vmDiv100 = div100(vm);
390
0
    if (vpDiv100 > vmDiv100) { // Optimization: remove two digits at a time (~86.2%).
391
0
      const uint64_t vrDiv100 = div100(vr);
392
0
      const uint32_t vrMod100 = ((uint32_t) vr) - 100 * ((uint32_t) vrDiv100);
393
0
      roundUp = vrMod100 >= 50;
394
0
      vr = vrDiv100;
395
0
      vp = vpDiv100;
396
0
      vm = vmDiv100;
397
0
      removed += 2;
398
0
    }
399
    // Loop iterations below (approximately), without optimization above:
400
    // 0: 0.03%, 1: 13.8%, 2: 70.6%, 3: 14.0%, 4: 1.40%, 5: 0.14%, 6+: 0.02%
401
    // Loop iterations below (approximately), with optimization above:
402
    // 0: 70.6%, 1: 27.8%, 2: 1.40%, 3: 0.14%, 4+: 0.02%
403
0
    for (;;) {
404
0
      const uint64_t vpDiv10 = div10(vp);
405
0
      const uint64_t vmDiv10 = div10(vm);
406
0
      if (vpDiv10 <= vmDiv10) {
407
0
        break;
408
0
      }
409
0
      const uint64_t vrDiv10 = div10(vr);
410
0
      const uint32_t vrMod10 = ((uint32_t) vr) - 10 * ((uint32_t) vrDiv10);
411
0
      roundUp = vrMod10 >= 5;
412
0
      vr = vrDiv10;
413
0
      vp = vpDiv10;
414
0
      vm = vmDiv10;
415
0
      ++removed;
416
0
    }
417
#ifdef RYU_DEBUG
418
    printf("%" PRIu64 " roundUp=%s\n", vr, roundUp ? "true" : "false");
419
    printf("vr is trailing zeros=%s\n", vrIsTrailingZeros ? "true" : "false");
420
#endif
421
    // We need to take vr + 1 if vr is outside bounds or we need to round up.
422
0
    output = vr + (vr == vm || roundUp);
423
0
  }
424
0
  const int32_t exp = e10 + removed;
425
426
#ifdef RYU_DEBUG
427
  printf("V+=%" PRIu64 "\nV =%" PRIu64 "\nV-=%" PRIu64 "\n", vp, vr, vm);
428
  printf("O=%" PRIu64 "\n", output);
429
  printf("EXP=%d\n", exp);
430
#endif
431
432
0
  floating_decimal_64 fd;
433
0
  fd.exponent = exp;
434
0
  fd.mantissa = output;
435
0
  return fd;
436
0
}
437
438
static inline uint64_t
439
pow_10(const int32_t exp)
440
0
{
441
0
  static const uint64_t POW_TABLE[18] = {
442
0
    1ULL,
443
0
    10ULL,
444
0
    100ULL,
445
0
    1000ULL,
446
0
    10000ULL,
447
448
0
    100000ULL,
449
0
    1000000ULL,
450
0
    10000000ULL,
451
0
    100000000ULL,
452
0
    1000000000ULL,
453
454
0
    10000000000ULL,
455
0
    100000000000ULL,
456
0
    1000000000000ULL,
457
0
    10000000000000ULL,
458
0
    100000000000000ULL,
459
460
0
    1000000000000000ULL,
461
0
    10000000000000000ULL,
462
0
    100000000000000000ULL
463
0
  };
464
0
  assert(exp <= 17);
465
0
  assert(exp >= 0);
466
0
  return POW_TABLE[exp];
467
0
}
468
469
static inline int to_chars_uint64(uint64_t output, uint32_t olength, char* const result)
470
0
{
471
0
  uint32_t i = 0;
472
473
  // We prefer 32-bit operations, even on 64-bit platforms.
474
  // We have at most 17 digits, and uint32_t can store 9 digits.
475
  // If output doesn't fit into uint32_t, we cut off 8 digits,
476
  // so the rest will fit into uint32_t.
477
0
  if ((output >> 32) != 0) {
478
    // Expensive 64-bit division.
479
0
    const uint64_t q = div1e8(output);
480
0
    uint32_t output2 = ((uint32_t) output) - 100000000 * ((uint32_t) q);
481
0
    output = q;
482
483
0
    const uint32_t c = output2 % 10000;
484
0
    output2 /= 10000;
485
0
    const uint32_t d = output2 % 10000;
486
0
    const uint32_t c0 = (c % 100) << 1;
487
0
    const uint32_t c1 = (c / 100) << 1;
488
0
    const uint32_t d0 = (d % 100) << 1;
489
0
    const uint32_t d1 = (d / 100) << 1;
490
0
    memcpy(result + olength - i - 2, DIGIT_TABLE + c0, 2);
491
0
    memcpy(result + olength - i - 4, DIGIT_TABLE + c1, 2);
492
0
    memcpy(result + olength - i - 6, DIGIT_TABLE + d0, 2);
493
0
    memcpy(result + olength - i - 8, DIGIT_TABLE + d1, 2);
494
0
    i += 8;
495
0
  }
496
497
0
  uint32_t output2 = (uint32_t) output;
498
0
  while (output2 >= 10000)
499
0
  {
500
0
  #ifdef __clang__ // https://bugs.llvm.org/show_bug.cgi?id=38217
501
0
    const uint32_t c = output2 - 10000 * (output2 / 10000);
502
  #else
503
    const uint32_t c = output2 % 10000;
504
  #endif
505
0
    output2 /= 10000;
506
0
    const uint32_t c0 = (c % 100) << 1;
507
0
    const uint32_t c1 = (c / 100) << 1;
508
0
    memcpy(result + olength - i - 2, DIGIT_TABLE + c0, 2);
509
0
    memcpy(result + olength - i - 4, DIGIT_TABLE + c1, 2);
510
0
    i += 4;
511
0
  }
512
513
0
  if (output2 >= 100)
514
0
  {
515
0
  #ifdef __clang__ // https://bugs.llvm.org/show_bug.cgi?id=38217
516
0
    const uint32_t c = (output2 % 100) << 1;
517
  #else
518
    const uint32_t c = (output2 - 100 * (output2 / 100)) << 1;
519
  #endif
520
0
    output2 /= 100;
521
0
    memcpy(result + olength - i - 2, DIGIT_TABLE + c, 2);
522
0
    i += 2;
523
0
  }
524
0
  if (output2 >= 10)
525
0
  {
526
0
    const uint32_t c = output2 << 1;
527
0
    memcpy(result + olength - i - 2, DIGIT_TABLE + c, 2);
528
0
    i += 2;
529
0
  } else {
530
0
    result[0] = (char) ('0' + output2);
531
0
    i += 1;
532
0
  }
533
534
0
  return i;
535
0
}
536
537
static inline int to_chars_fixed(const floating_decimal_64 v, const bool sign, uint32_t precision, char* const result)
538
0
{
539
0
  uint64_t output = v.mantissa;
540
0
  uint32_t olength = decimalLength17(output);
541
0
  int32_t exp = v.exponent;
542
0
  uint64_t integer_part;
543
0
  uint32_t integer_part_length = 0;
544
0
  uint64_t decimal_part;
545
0
  uint32_t decimal_part_length = 0;
546
0
  uint32_t trailing_integer_zeros = 0;
547
0
  uint32_t leading_decimal_zeros = 0;
548
549
0
  if (exp >= 0)
550
0
  {
551
0
    integer_part = output;
552
0
    integer_part_length = olength;
553
0
    trailing_integer_zeros = exp;
554
0
    decimal_part = 0;
555
0
  }
556
0
  else
557
0
  {
558
    /* Adapt the decimal digits to the desired precision */
559
0
    if (precision < (uint32_t) -exp)
560
0
    {
561
0
      int32_t digits_to_trim = -exp - precision;
562
0
      if (digits_to_trim > (int32_t) olength)
563
0
      {
564
0
        output = 0;
565
0
        exp = 0;
566
0
      }
567
0
      else
568
0
      {
569
0
        const uint64_t divisor = pow_10(digits_to_trim);
570
0
        const uint64_t divisor_half = divisor / 2;
571
0
        const uint64_t outputDiv = output / divisor;
572
0
        const uint64_t remainder = output - outputDiv * divisor;
573
574
0
        output = outputDiv;
575
0
        exp += digits_to_trim;
576
577
0
        if (remainder > divisor_half || (remainder == divisor_half && (output & 1)))
578
0
        {
579
0
          output++;
580
0
          olength = decimalLength17(output);
581
0
        }
582
0
        else
583
0
        {
584
0
          olength -= digits_to_trim;
585
0
        }
586
587
0
        while (output && output % 10 == 0)
588
0
        {
589
0
          output = div10(output);
590
0
          exp++;
591
0
          olength--;
592
0
        }
593
0
      }
594
0
    }
595
596
0
    int32_t nexp = -exp;
597
0
    if (exp >= 0)
598
0
    {
599
0
      integer_part = output;
600
0
      integer_part_length = olength;
601
0
      trailing_integer_zeros = exp;
602
0
      decimal_part = 0;
603
0
    }
604
0
    else if (nexp < (int32_t) olength)
605
0
    {
606
0
      uint64_t p = pow_10(nexp);
607
0
      integer_part = output / p;
608
0
      decimal_part = output % p;
609
0
      integer_part_length = olength - nexp;
610
0
      decimal_part_length = olength - integer_part_length;
611
0
      if (decimal_part < pow_10(decimal_part_length - 1))
612
0
      {
613
        /* The decimal part had leading zeros (e.g. 123.0001) which were lost */
614
0
        decimal_part_length = decimalLength17(decimal_part);
615
0
        leading_decimal_zeros = olength - integer_part_length - decimal_part_length;
616
0
      }
617
0
    }
618
0
    else
619
0
    {
620
0
      integer_part = 0;
621
0
      decimal_part = output;
622
0
      decimal_part_length = olength;
623
0
      leading_decimal_zeros = nexp - olength;
624
0
    }
625
0
  }
626
627
#ifdef RYU_DEBUG
628
  printf("DIGITS=%" PRIu64 "\n", v.mantissa);
629
  printf("EXP=%d\n", v.exponent);
630
  printf("INTEGER=%lu\n", integer_part);
631
  printf("DECIMAL=%lu\n", decimal_part);
632
  printf("EXTRA TRAILING ZEROS=%d\n", trailing_integer_zeros);
633
  printf("EXTRA LEADING ZEROS=%d\n", leading_decimal_zeros);
634
#endif
635
636
  /* If we have removed all digits, it may happen that we have -0 and we want it to be just 0 */
637
0
  int index = 0;
638
0
  if (sign && (integer_part || decimal_part))
639
0
  {
640
0
    result[index++] = '-';
641
0
  }
642
643
0
  index += to_chars_uint64(integer_part, integer_part_length, &result[index]);
644
0
  for (uint32_t i = 0; i < trailing_integer_zeros; i++)
645
0
    result[index++] = '0';
646
647
0
  if (decimal_part)
648
0
  {
649
0
    result[index++] = '.';
650
0
    for (uint32_t i = 0; i < leading_decimal_zeros; i++)
651
0
      result[index++] = '0';
652
0
    index += to_chars_uint64(decimal_part, decimal_part_length, &result[index]);
653
0
  }
654
655
0
  return index;
656
0
}
657
658
static inline bool d2d_small_int(const uint64_t ieeeMantissa, const uint32_t ieeeExponent,
659
0
  floating_decimal_64* const v) {
660
0
  const uint64_t m2 = (1ull << DOUBLE_MANTISSA_BITS) | ieeeMantissa;
661
0
  const int32_t e2 = (int32_t) ieeeExponent - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS;
662
663
0
  if (e2 > 0) {
664
    // f = m2 * 2^e2 >= 2^53 is an integer.
665
    // Ignore this case for now.
666
0
    return false;
667
0
  }
668
669
0
  if (e2 < -52) {
670
    // f < 1.
671
0
    return false;
672
0
  }
673
674
  // Since 2^52 <= m2 < 2^53 and 0 <= -e2 <= 52: 1 <= f = m2 / 2^-e2 < 2^53.
675
  // Test if the lower -e2 bits of the significand are 0, i.e. whether the fraction is 0.
676
0
  const uint64_t mask = (1ull << -e2) - 1;
677
0
  const uint64_t fraction = m2 & mask;
678
0
  if (fraction != 0) {
679
0
    return false;
680
0
  }
681
682
  // f is an integer in the range [1, 2^53).
683
  // Note: mantissa might contain trailing (decimal) 0's.
684
  // Note: since 2^53 < 10^16, there is no need to adjust decimalLength17().
685
0
  v->mantissa = m2 >> -e2;
686
0
  v->exponent = 0;
687
0
  return true;
688
0
}
689
690
0
int d2sfixed_buffered_n(double f, uint32_t precision, char* result) {
691
  // Step 1: Decode the floating-point number, and unify normalized and subnormal cases.
692
0
  const uint64_t bits = double_to_bits(f);
693
694
#ifdef RYU_DEBUG
695
  printf("IN=");
696
  for (int32_t bit = 63; bit >= 0; --bit) {
697
    printf("%d", (int) ((bits >> bit) & 1));
698
  }
699
  printf("\n");
700
#endif
701
702
  // Decode bits into sign, mantissa, and exponent.
703
0
  const bool ieeeSign = ((bits >> (DOUBLE_MANTISSA_BITS + DOUBLE_EXPONENT_BITS)) & 1) != 0;
704
0
  const uint64_t ieeeMantissa = bits & ((1ull << DOUBLE_MANTISSA_BITS) - 1);
705
0
  const uint32_t ieeeExponent = (uint32_t) ((bits >> DOUBLE_MANTISSA_BITS) & ((1u << DOUBLE_EXPONENT_BITS) - 1));
706
  // Case distinction; exit early for the easy cases.
707
0
  if (ieeeExponent == ((1u << DOUBLE_EXPONENT_BITS) - 1u) || (ieeeExponent == 0 && ieeeMantissa == 0)) {
708
0
    return copy_special_str(result, ieeeSign, ieeeExponent, ieeeMantissa);
709
0
  }
710
711
0
  floating_decimal_64 v;
712
0
  const bool isSmallInt = d2d_small_int(ieeeMantissa, ieeeExponent, &v);
713
0
  if (isSmallInt) {
714
    // For small integers in the range [1, 2^53), v.mantissa might contain trailing (decimal) zeros.
715
    // For scientific notation we need to move these zeros into the exponent.
716
    // (This is not needed for fixed-point notation, so it might be beneficial to trim
717
    // trailing zeros in to_chars only if needed - once fixed-point notation output is implemented.)
718
0
    for (;;) {
719
0
      const uint64_t q = div10(v.mantissa);
720
0
      const uint32_t r = ((uint32_t) v.mantissa) - 10 * ((uint32_t) q);
721
0
      if (r != 0) {
722
0
        break;
723
0
      }
724
0
      v.mantissa = q;
725
0
      ++v.exponent;
726
0
    }
727
0
  } else {
728
0
    v = d2d(ieeeMantissa, ieeeExponent);
729
0
  }
730
731
0
  return to_chars_fixed(v, ieeeSign, precision, result);
732
0
}
733
734
0
int d2sexp_buffered_n(double f, uint32_t precision, char* result) {
735
  // Step 1: Decode the floating-point number, and unify normalized and subnormal cases.
736
0
  const uint64_t bits = double_to_bits(f);
737
738
#ifdef RYU_DEBUG
739
  printf("IN=");
740
  for (int32_t bit = 63; bit >= 0; --bit) {
741
    printf("%d", (int) ((bits >> bit) & 1));
742
  }
743
  printf("\n");
744
#endif
745
746
  // Decode bits into sign, mantissa, and exponent.
747
0
  const bool ieeeSign = ((bits >> (DOUBLE_MANTISSA_BITS + DOUBLE_EXPONENT_BITS)) & 1) != 0;
748
0
  const uint64_t ieeeMantissa = bits & ((1ull << DOUBLE_MANTISSA_BITS) - 1);
749
0
  const uint32_t ieeeExponent = (uint32_t) ((bits >> DOUBLE_MANTISSA_BITS) & ((1u << DOUBLE_EXPONENT_BITS) - 1));
750
  // Case distinction; exit early for the easy cases.
751
0
  if (ieeeExponent == ((1u << DOUBLE_EXPONENT_BITS) - 1u) || (ieeeExponent == 0 && ieeeMantissa == 0)) {
752
0
    return copy_special_str(result, ieeeSign, ieeeExponent, ieeeMantissa);
753
0
  }
754
755
0
  floating_decimal_64 v;
756
0
  const bool isSmallInt = d2d_small_int(ieeeMantissa, ieeeExponent, &v);
757
0
  if (isSmallInt) {
758
    // For small integers in the range [1, 2^53), v.mantissa might contain trailing (decimal) zeros.
759
    // For scientific notation we need to move these zeros into the exponent.
760
    // (This is not needed for fixed-point notation, so it might be beneficial to trim
761
    // trailing zeros in to_chars only if needed - once fixed-point notation output is implemented.)
762
0
    for (;;) {
763
0
      const uint64_t q = div10(v.mantissa);
764
0
      const uint32_t r = ((uint32_t) v.mantissa) - 10 * ((uint32_t) q);
765
0
      if (r != 0) {
766
0
        break;
767
0
      }
768
0
      v.mantissa = q;
769
0
      ++v.exponent;
770
0
    }
771
0
  } else {
772
0
    v = d2d(ieeeMantissa, ieeeExponent);
773
0
  }
774
775
  // Print first the mantissa using the fixed point notation, then add the exponent manually
776
0
  const int32_t olength = (int32_t) decimalLength17(v.mantissa);
777
0
  const int32_t original_ieeeExponent = v.exponent + olength - 1;
778
0
  v.exponent = 1 - olength;
779
0
  int index = to_chars_fixed(v, ieeeSign, precision, result);
780
781
  // Print the exponent.
782
0
  result[index++] = 'e';
783
0
  int32_t exp = original_ieeeExponent;
784
0
  if (exp < 0) {
785
0
    result[index++] = '-';
786
0
    exp = -exp;
787
0
  }
788
0
  else
789
0
  {
790
0
  result[index++] = '+';
791
0
  }
792
793
0
  if (exp >= 100) {
794
0
    const int32_t c = exp % 10;
795
0
    memcpy(result + index, DIGIT_TABLE + 2 * (exp / 10), 2);
796
0
    result[index + 2] = (char) ('0' + c);
797
0
    index += 3;
798
0
  } else if (exp >= 10) {
799
0
    memcpy(result + index, DIGIT_TABLE + 2 * exp, 2);
800
0
    index += 2;
801
0
  } else {
802
0
    result[index++] = (char) ('0' + exp);
803
0
  }
804
805
0
  return index;
806
0
}