Coverage Report

Created: 2026-11-10 14:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
src/integer.c
Line
Count
Source
1
#include "prism/internal/integer.h"
2
3
#include "prism/compiler/align.h"
4
#include "prism/compiler/inline.h"
5
6
#include "prism/internal/allocator.h"
7
#include "prism/internal/arena.h"
8
#include "prism/internal/assert.h"
9
#include "prism/internal/bignum.h"
10
#include "prism/internal/bit.h"
11
#include "prism/internal/buffer.h"
12
#include "prism/internal/oom.h"
13
14
/* Include sys/types.h before inttypes.h to work around an issue with certain
15
 * versions of GCC and newlib which causes omission of PRIu64 and the other
16
 * 64-bit macros. */
17
#include <sys/types.h>
18
#include <inttypes.h>
19
20
#include <stdbool.h>
21
#include <stddef.h>
22
#include <stdlib.h>
23
#include <string.h>
24
25
/**
26
 * When parsing long decimal digits, we switch to a divide-and-conquer approach
27
 * once it gets really long because we start to see the impact of an O(n^1.58)
28
 * vs an O(n^2) algorithm.
29
 */
30
#ifndef PM_INTEGER_DIVIDE_THRESHOLD
31
#define PM_INTEGER_DIVIDE_THRESHOLD 224
32
#endif
33
34
/**
35
 * When printing integers of many words, we switch to a divide-and-conquer
36
 * approach for the same reason as parsing: the repeated division by 10**9 is
37
 * O(n^2), while the divide and conquer is O(n^1.58). Below this many words, the
38
 * scratch space and the powers of two that the divide and conquer needs cost
39
 * more than it saves.
40
 */
41
1.24k
#define PM_INTEGER_STRING_THRESHOLD 48
42
43
/**
44
 * Within the divide and conquer, pieces of at most this many words are
45
 * converted by repeated division by 10**9. This is lower than
46
 * PM_INTEGER_STRING_THRESHOLD because the pieces share the scratch space and
47
 * the powers of two, so they do not pay for them again.
48
 */
49
0
#define PM_INTEGER_STRING_LEAF 8
50
51
/**
52
 * The values of a hexadecimal digit, where the index is the ASCII character.
53
 */
54
static const int8_t pm_integer_parse_digit_values[256] = {
55
/*   0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
56
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x */
57
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 1x */
58
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 2x */
59
     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1, /* 3x */
60
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 4x */
61
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 5x */
62
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 6x */
63
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 7x */
64
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 8x */
65
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 9x */
66
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* Ax */
67
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* Bx */
68
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* Cx */
69
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* Dx */
70
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* Ex */
71
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* Fx */
72
};
73
74
/**
75
 * Return the value of a hexadecimal digit in a uint8_t.
76
 */
77
static uint8_t
78
48.1k
pm_integer_parse_digit(const uint8_t character) {
79
48.1k
    int8_t value = pm_integer_parse_digit_values[character];
80
48.1k
    PRISM_ASSERT(value != -1 && "invalid digit");
  Branch (80:5): [True: 0, False: 48.1k]
  Branch (80:5): [True: 0, False: 0]
  Branch (80:5): [True: 48.1k, False: 0]
  Branch (80:5): [True: 48.1k, False: 0]
81
82
48.1k
    return (uint8_t) value;
83
48.1k
}
84
85
/**
86
 * Whether a character between the digits of a number is skipped. Underscores
87
 * separate digits, and the decimal point of a float rational like 1.5r does not
88
 * change its numerator, which is all of its digits.
89
 */
90
static PRISM_INLINE bool
91
75.6k
pm_integer_separator(uint8_t character) {
92
75.6k
    return character == '_' || 
character == '.'73.9k
;
  Branch (92:12): [True: 1.63k, False: 73.9k]
  Branch (92:32): [True: 1.34k, False: 72.6k]
93
75.6k
}
94
95
/**
96
 * Store a bignum whose words are allocated in the arena, with room for capacity
97
 * words, into an integer. An integer with at most two words stores them inline,
98
 * so all of the arena words are given back; otherwise only the unused ones are.
99
 */
100
static void
101
2.01k
pm_integer_from_bignum(pm_arena_t *arena, pm_integer_t *integer, const pm_bignum_t *bignum, uint32_t capacity) {
102
2.01k
    if (bignum->length <= 2) {
  Branch (102:9): [True: 1.26k, False: 750]
103
1.26k
        uint64_t value = pm_bignum_uint64(bignum);
104
1.26k
        pm_arena_realloc(arena, bignum->words, 0, sizeof(uint32_t) * capacity, PRISM_ALIGNOF(uint32_t));
105
1.26k
        *integer = pm_integer_uint64(value);
106
1.26k
    } else {
107
750
        uint32_t *words = (uint32_t *) pm_arena_realloc(arena, bignum->words, sizeof(uint32_t) * bignum->length, sizeof(uint32_t) * capacity, PRISM_ALIGNOF(uint32_t));
108
750
        *integer = (pm_integer_t) { .length = bignum->length, .words = { .values = words } };
109
750
    }
110
2.01k
}
111
112
/**
113
 * Parse the digits of an integer in a power-of-two base that does not fit in
114
 * two words. Every digit but the leading one contributes exactly the same number
115
 * of bits, so the exact number of words is known before parsing, and the digits
116
 * are packed directly into words allocated from the arena.
117
 */
118
static void
119
24
pm_integer_parse_powof2(pm_arena_t *arena, pm_integer_t *integer, uint32_t base, uint32_t digits, const uint8_t *start, const uint8_t *end) {
120
24
    static const uint8_t digit_bits[16] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 };
121
24
    uint32_t leading_bits = digit_bits[pm_integer_parse_digit(*start)];
122
123
24
    uint32_t bit = (uint32_t) pm_ctzll(base);
124
24
    PRISM_ASSERT(bit >= 1 && bit <= 4);
  Branch (124:5): [True: 0, False: 24]
  Branch (124:5): [True: 0, False: 0]
  Branch (124:5): [True: 24, False: 0]
  Branch (124:5): [True: 24, False: 0]
125
126
24
    uint32_t length = (uint32_t) (((uint64_t) (digits - 1) * bit + leading_bits + 31) / 32);
127
24
    PRISM_ASSERT(length > 2);
  Branch (127:5): [True: 0, False: 24]
  Branch (127:5): [True: 24, False: 0]
128
129
24
    uint32_t *words = pm_arena_zalloc(arena, sizeof(uint32_t) * length, PRISM_ALIGNOF(uint32_t));
130
24
    uint64_t bit_position = 0;
131
132
993
    for (const uint8_t *cursor = end; cursor > start;) {
  Branch (132:39): [True: 969, False: 24]
133
969
        if (pm_integer_separator(*--cursor)) 
continue98
;
  Branch (133:13): [True: 98, False: 871]
134
871
        uint32_t value = pm_integer_parse_digit(*cursor);
135
136
871
        uint32_t index = (uint32_t) (bit_position / 32);
137
871
        uint32_t shift = (uint32_t) (bit_position % 32);
138
139
871
        words[index] |= value << shift;
140
871
        if (32 - shift < bit && 
index + 1 < length32
)
words[index + 1] |= value >> (32 - shift)30
;
  Branch (140:13): [True: 32, False: 839]
  Branch (140:33): [True: 30, False: 2]
141
142
871
        bit_position += bit;
143
871
    }
144
145
24
    *integer = (pm_integer_t) { .length = length, .words = { .values = words } };
146
24
}
147
148
/**
149
 * The number of words needed to hold a decimal integer with the given number
150
 * of digits. A number with d digits is below 10**d, so it needs at most:
151
 *
152
 *     d * log2(10) + 1
153
 *
154
 * bits, which rounds up to at most one word more than the whole words below
155
 * that count. To find log2(10), we approximate it as 3402/1024, which is
156
 * slightly greater than the actual value so it does not undercount.
157
 */
158
static PRISM_INLINE uint32_t
159
845
pm_integer_decimal_words(uint64_t digits) {
160
845
    return (uint32_t) ((digits * 3402 / 1024) / 32 + 1);
161
845
}
162
163
/**
164
 * The number of words of storage needed to convert nchunks chunks of nine
165
 * decimal digits, which is one word more than the value needs. The conversion
166
 * multiplies the high half by a power of ten into this storage, and
167
 * pm_bignum_multiply writes the sum of its factors' lengths before it trims a
168
 * zero top word. Each factor's length rounds its bits up to a whole word, so
169
 * that sum can be one word more than the product needs.
170
 */
171
static PRISM_INLINE uint32_t
172
185
pm_integer_chunks_words(uint32_t nchunks) {
173
185
    return pm_integer_decimal_words((uint64_t) nchunks * 9) + 1;
174
185
}
175
176
/**
177
 * Convert nchunks of nine decimal digits into a bignum. Do this by effectively
178
 * converting the base of the number from 10**9 to 2**32. The result's storage
179
 * must have room for pm_integer_chunks_words(nchunks) words.
180
 */
181
static void
182
137
pm_integer_parse_decimal_divide_chunks(pm_bignum_t *result, uint32_t nchunks, const uint32_t *chunks, const pm_bignum_t *powers, pm_bignum_scratch_t *scratch) {
183
137
    if (nchunks <= PM_INTEGER_DIVIDE_THRESHOLD) {
  Branch (183:9): [True: 89, False: 48]
184
89
        result->length = 0;
185
585
        for (uint32_t index = nchunks; index > 0; 
index--496
)
pm_bignum_mul_add(result, 496
PM_BIGNUM_DECIMAL_BASE496
, chunks[index - 1]);
  Branch (185:40): [True: 496, False: 89]
186
89
    } else {
187
48
        uint32_t level = pm_bsrll((uint64_t) nchunks - 1);
188
48
        uint32_t split = (uint32_t) 1 << level;
189
190
48
        uint32_t *saved = scratch->cursor;
191
48
        pm_bignum_t high = { .length = 0, .words = pm_bignum_scratch_take(scratch, pm_integer_chunks_words(nchunks - split)) };
192
48
        pm_integer_parse_decimal_divide_chunks(&high, nchunks - split, chunks + split, powers, scratch);
193
194
48
        PRISM_ASSERT(high.length + powers[level].length <= pm_integer_chunks_words(nchunks));
  Branch (194:9): [True: 0, False: 48]
  Branch (194:9): [True: 48, False: 0]
195
48
        pm_bignum_multiply(result, &high, &powers[level], scratch);
196
48
        scratch->cursor = saved;
197
198
48
        pm_bignum_t low = { .length = 0, .words = pm_bignum_scratch_take(scratch, pm_integer_chunks_words(split)) };
199
48
        pm_integer_parse_decimal_divide_chunks(&low, split, chunks, powers, scratch);
200
48
        pm_bignum_add(result, &low);
201
48
        scratch->cursor = saved;
202
48
    }
203
137
}
204
205
/**
206
 * Parse the digits of a decimal integer of more than
207
 * PM_INTEGER_DIVIDE_THRESHOLD chunks of nine digits by divide and conquer. The
208
 * digits are packed into chunks, the powers of ten that the splits need are
209
 * computed by repeated squaring, and the result is converted straight into
210
 * words allocated from the arena. Everything else lives in one block of
211
 * scratch space from the heap, sized for the worst case: the chunks, the
212
 * powers, and the halves and products of the deepest chain of splits, with
213
 * Karatsuba's temporaries bounded by 12 times the longer factor's length.
214
 */
215
static void
216
41
pm_integer_parse_decimal_divide(pm_arena_t *arena, pm_integer_t *integer, uint32_t digits, const uint8_t *start, const uint8_t *end) {
217
41
    uint32_t nchunks = (uint32_t) (((uint64_t) digits + 8) / 9);
218
41
    uint32_t capacity = pm_integer_chunks_words(nchunks);
219
220
41
    pm_bignum_t result = {
221
41
        .length = 0,
222
41
        .words = (uint32_t *) pm_arena_alloc(arena, sizeof(uint32_t) * capacity, PRISM_ALIGNOF(uint32_t))
223
41
    };
224
225
    /* The scratch space is about 12 times the number of chunks, which can
226
     * exceed 32 bits, and on a 32-bit platform its size in bytes can exceed
227
     * size_t. */
228
41
    uint64_t scratch_size = (uint64_t) nchunks + 12 * (uint64_t) capacity + 1024;
229
41
    if (scratch_size > SIZE_MAX / sizeof(uint32_t)) 
PRISM_OOM0
();
  Branch (229:9): [True: 0, False: 41]
230
231
41
    uint32_t *allocation = (uint32_t *) xmalloc(sizeof(uint32_t) * (size_t) scratch_size);
232
41
    if (allocation == NULL) 
PRISM_OOM0
();
  Branch (232:9): [True: 0, False: 41]
233
41
    pm_bignum_scratch_t scratch = { .cursor = allocation, .end = allocation + (size_t) scratch_size };
234
235
    /* Pack the digits into chunks of nine, least significant first. The most
236
     * significant chunk takes the leftover digits so the rest are exactly
237
     * nine. */
238
41
    uint32_t *chunks = pm_bignum_scratch_take(&scratch, nchunks);
239
41
    uint32_t chunk_size = digits % 9 == 0 ? 
93
:
digits % 938
;
  Branch (239:27): [True: 3, False: 38]
240
41
    uint32_t chunk_digits = 0;
241
41
    uint32_t chunk_index = nchunks;
242
41
    uint32_t chunk = 0;
243
244
4.38k
    for (const uint8_t *cursor = start; cursor < end; 
cursor++4.34k
) {
  Branch (244:41): [True: 4.34k, False: 41]
245
4.34k
        if (pm_integer_separator(*cursor)) 
continue62
;
  Branch (245:13): [True: 62, False: 4.28k]
246
4.28k
        chunk = chunk * 10 + pm_integer_parse_digit(*cursor);
247
248
4.28k
        if (++chunk_digits == chunk_size) {
  Branch (248:13): [True: 496, False: 3.78k]
249
496
            chunks[--chunk_index] = chunk;
250
496
            chunk_size = 9;
251
496
            chunk_digits = 0;
252
496
            chunk = 0;
253
496
        }
254
4.28k
    }
255
41
    PRISM_ASSERT(chunk_index == 0);
  Branch (255:5): [True: 0, False: 41]
  Branch (255:5): [True: 41, False: 0]
256
257
    /* powers[level] is 10**(9 * 2**level), for every level a split uses. */
258
41
    pm_bignum_t powers[64];
259
41
    uint32_t level = 0;
260
41
    powers[level].words = pm_bignum_scratch_take(&scratch, 1);
261
41
    powers[level].words[0] = PM_BIGNUM_DECIMAL_BASE;
262
41
    powers[level].length = 1;
263
264
171
    for (uint32_t split = 2; split < nchunks; 
split *= 2130
) {
  Branch (264:30): [True: 130, False: 41]
265
130
        const pm_bignum_t *previous = &powers[level++];
266
130
        powers[level].words = pm_bignum_scratch_take(&scratch, 2 * previous->length);
267
130
        pm_bignum_multiply(&powers[level], previous, previous, &scratch);
268
130
    }
269
270
41
    pm_integer_parse_decimal_divide_chunks(&result, nchunks, chunks, powers, &scratch);
271
41
    xfree_sized(allocation, sizeof(uint32_t) * (size_t) scratch_size);
272
273
41
    PRISM_ASSERT(result.length > 2 && result.length <= capacity);
  Branch (273:5): [True: 0, False: 41]
  Branch (273:5): [True: 0, False: 0]
  Branch (273:5): [True: 41, False: 0]
  Branch (273:5): [True: 41, False: 0]
274
41
    pm_integer_from_bignum(arena, integer, &result, capacity);
275
41
}
276
277
/**
278
 * Parse the digits of a decimal integer that does not fit in two words. The
279
 * words are built in place in the arena: starting from zero, the number is
280
 * multiplied by 10**9 and the next nine digits are added, until every digit is
281
 * consumed. The first chunk takes the leftover digits so the rest are exactly
282
 * nine.
283
 */
284
static void
285
660
pm_integer_parse_decimal_schoolbook(pm_arena_t *arena, pm_integer_t *integer, uint32_t digits, const uint8_t *start, const uint8_t *end) {
286
660
    static const uint32_t powof10[10] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
287
288
    /* The words that turn out to be unneeded are given back to the arena
289
     * below. */
290
660
    uint32_t capacity = pm_integer_decimal_words(digits);
291
660
    pm_bignum_t bignum = {
292
660
        .length = 0,
293
660
        .words = (uint32_t *) pm_arena_alloc(arena, sizeof(uint32_t) * capacity, PRISM_ALIGNOF(uint32_t))
294
660
    };
295
296
660
    uint32_t chunk_size = digits % 9 == 0 ? 
927
:
digits % 9633
;
  Branch (296:27): [True: 27, False: 633]
297
660
    uint32_t chunk_digits = 0;
298
660
    uint32_t chunk = 0;
299
300
20.3k
    for (const uint8_t *cursor = start; cursor < end; 
cursor++19.7k
) {
  Branch (300:41): [True: 19.7k, False: 660]
301
19.7k
        if (pm_integer_separator(*cursor)) 
continue313
;
  Branch (301:13): [True: 313, False: 19.3k]
302
19.3k
        chunk = chunk * 10 + pm_integer_parse_digit(*cursor);
303
304
19.3k
        if (++chunk_digits == chunk_size) {
  Branch (304:13): [True: 2.50k, False: 16.8k]
305
2.50k
            pm_bignum_mul_add(&bignum, powof10[chunk_size], chunk);
306
307
2.50k
            chunk_size = 9;
308
2.50k
            chunk_digits = 0;
309
2.50k
            chunk = 0;
310
2.50k
        }
311
19.3k
    }
312
313
660
    PRISM_ASSERT(bignum.length > 2 && bignum.length <= capacity);
  Branch (313:5): [True: 0, False: 660]
  Branch (313:5): [True: 0, False: 0]
  Branch (313:5): [True: 660, False: 0]
  Branch (313:5): [True: 660, False: 0]
314
660
    pm_integer_from_bignum(arena, integer, &bignum, capacity);
315
660
}
316
317
/**
318
 * Parse the digits of an integer in the given base, after any prefix.
319
 */
320
static void
321
7.32k
pm_integer_parse_digits(pm_arena_t *arena, pm_integer_t *integer, uint32_t base, const uint8_t *start, const uint8_t *end) {
322
    /* Leading zeros do not change the value, so skip them here and the paths
323
     * below always start at a nonzero digit. */
324
9.85k
    while (start < end && 
(8.62k
*start == '0'8.62k
||
pm_integer_separator(*start)6.27k
))
start++2.53k
;
  Branch (324:12): [True: 8.62k, False: 1.22k]
  Branch (324:28): [True: 2.35k, False: 6.27k]
  Branch (324:45): [True: 183, False: 6.09k]
325
326
    /* Everything has been consumed if the integer is zero, or if it is invalid
327
     * and has no digits. Either way the result is zero. */
328
7.32k
    if (start >= end) {
  Branch (328:9): [True: 1.22k, False: 6.09k]
329
1.22k
        *integer = (pm_integer_t) { 0 };
330
1.22k
        return;
331
1.22k
    }
332
333
    /* Accumulate into a uint64_t, which covers every integer whose words are
334
     * stored inline. value * base + digit overflows exactly when value
335
     * is past limit, or equal to it with digit past limit_digit. */
336
6.09k
    const uint64_t limit = UINT64_MAX / base;
337
6.09k
    const uint64_t limit_digit = UINT64_MAX % base;
338
339
6.09k
    const uint8_t *cursor = start;
340
6.09k
    uint64_t value = (uint64_t) pm_integer_parse_digit(*cursor++);
341
342
24.6k
    for (; cursor < end; 
cursor++18.5k
) {
  Branch (342:12): [True: 19.3k, False: 5.36k]
343
19.3k
        if (pm_integer_separator(*cursor)) 
continue1.85k
;
  Branch (343:13): [True: 1.85k, False: 17.4k]
344
17.4k
        uint64_t digit = (uint64_t) pm_integer_parse_digit(*cursor);
345
346
17.4k
        if (value > limit || 
(16.7k
value == limit16.7k
&&
digit > limit_digit1
)) {
  Branch (346:13): [True: 725, False: 16.7k]
  Branch (346:31): [True: 1, False: 16.7k]
  Branch (346:49): [True: 0, False: 1]
347
725
            uint32_t digits = 0;
348
25.7k
            for (const uint8_t *scan = start; scan < end; 
scan++25.0k
) {
  Branch (348:47): [True: 25.0k, False: 725]
349
25.0k
                if (!pm_integer_separator(*scan)) 
digits++24.5k
;
  Branch (349:21): [True: 24.5k, False: 473]
350
25.0k
            }
351
352
725
            if (base != 10) {
  Branch (352:17): [True: 24, False: 701]
353
24
                pm_integer_parse_powof2(arena, integer, base, digits, start, end);
354
701
            } else if (((uint64_t) digits + 8) / 9 > PM_INTEGER_DIVIDE_THRESHOLD) {
  Branch (354:24): [True: 41, False: 660]
355
41
                pm_integer_parse_decimal_divide(arena, integer, digits, start, end);
356
660
            } else {
357
660
                pm_integer_parse_decimal_schoolbook(arena, integer, digits, start, end);
358
660
            }
359
360
725
            return;
361
725
        }
362
363
16.7k
        value = value * base + digit;
364
16.7k
    }
365
366
5.36k
    *integer = pm_integer_uint64(value);
367
5.36k
}
368
369
/**
370
 * Parse an integer from a string. This assumes that the format of the integer
371
 * has already been validated, as internal validation checks are not performed
372
 * here.
373
 */
374
void
375
6.02k
pm_integer_parse(pm_arena_t *arena, pm_integer_t *integer, pm_integer_base_t base, const uint8_t *start, const uint8_t *end) {
376
    /* Ignore unary +. Unary - is parsed differently and will not end up here.
377
     * Instead, it will modify the parsed integer later. */
378
6.02k
    if (*start == '+') 
start++10
;
  Branch (378:9): [True: 10, False: 6.01k]
379
380
    /* Skip past any prefixes. */
381
6.02k
    switch (base) {
  Branch (381:13): [True: 6.02k, False: 0]
382
383
        case PM_INTEGER_BASE_BINARY:
  Branch (382:9): [True: 383, False: 5.64k]
383
383
            start += 2; /* 0b */
384
383
            break;
385
1.36k
        case PM_INTEGER_BASE_OCTAL:
  Branch (385:9): [True: 1.36k, False: 4.66k]
386
1.36k
            start++; /* 0 */
387
1.36k
            if (*start == '_' || 
*start == 'o'1.34k
||
*start == 'O'759
)
start++613
; /* o */
  Branch (387:17): [True: 20, False: 1.34k]
  Branch (387:34): [True: 584, False: 759]
  Branch (387:51): [True: 9, False: 750]
388
1.36k
            break;
389
3.89k
        case PM_INTEGER_BASE_DECIMAL:
  Branch (389:9): [True: 3.89k, False: 2.13k]
390
3.89k
            if (*start == '0' && 
(end - start) > 1840
)
start += 2510
; /* 0d */
  Branch (390:17): [True: 840, False: 3.05k]
  Branch (390:34): [True: 510, False: 330]
391
3.89k
            break;
392
387
        case PM_INTEGER_BASE_HEXADECIMAL:
  Branch (392:9): [True: 387, False: 5.64k]
393
387
            start += 2; /* 0x */
394
387
            break;
395
6.02k
    }
396
397
6.02k
    pm_integer_parse_digits(arena, integer, (uint32_t) base, start, end);
398
6.02k
}
399
400
/**
401
 * Parse a float rational literal like 1.5r, given its digits and decimal point
402
 * without the r suffix, into a numerator and denominator in lowest terms. Its
403
 * value is its digits read as an integer over 10**k, where k is the number of
404
 * digits after the decimal point. Since 10**k is 2**k * 5**k, the greatest
405
 * common divisor of the two is a power of two times a power of five, so the
406
 * fraction is reduced by dividing those out of the numerator and leaving them
407
 * out of the denominator.
408
 */
409
void
410
1.29k
pm_integer_parse_rational(pm_arena_t *arena, pm_integer_t *numerator, pm_integer_t *denominator, const uint8_t *start, const uint8_t *end) {
411
1.29k
    static const uint32_t powof5[14] = { 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625, 1220703125 };
412
413
1.29k
    if (*start == '+') 
start++4
;
  Branch (413:9): [True: 4, False: 1.28k]
414
415
1.29k
    const uint8_t *point = memchr(start, '.', (size_t) (end - start));
416
1.29k
    PRISM_ASSERT(point != NULL);
  Branch (416:5): [True: 0, False: 1.29k]
  Branch (416:5): [True: 1.29k, False: 0]
417
418
    /* Each trailing zero after the decimal point divides both sides by 10, so
419
     * drop them before parsing. */
420
1.47k
    
while (1.29k
end > point + 1 &&
(1.40k
end[-1] == '0'1.40k
||
end[-1] == '_'1.27k
))
end--187
;
  Branch (420:12): [True: 1.40k, False: 77]
  Branch (420:32): [True: 129, False: 1.27k]
  Branch (420:50): [True: 58, False: 1.21k]
421
422
1.29k
    uint32_t exponent = 0;
423
4.17k
    for (const uint8_t *cursor = point + 1; cursor < end; 
cursor++2.88k
) {
  Branch (423:45): [True: 2.88k, False: 1.29k]
424
2.88k
        if (*cursor != '_') exponent++;
  Branch (424:13): [True: 2.88k, False: 0]
425
2.88k
    }
426
427
1.29k
    pm_integer_parse_digits(arena, numerator, 10, start, end);
428
1.29k
    uint32_t twos = 0;
429
1.29k
    uint32_t fives = 0;
430
431
1.29k
    if (numerator->length > 0 && 
exponent > 01.27k
) {
  Branch (431:9): [True: 1.27k, False: 20]
  Branch (431:34): [True: 1.21k, False: 57]
432
1.21k
        uint32_t length = numerator->length;
433
1.21k
        pm_bignum_t bignum = {
434
1.21k
            .length = length,
435
1.21k
            .words = length <= 2 ? 
numerator->words.value1.18k
:
numerator->words.values26
  Branch (435:22): [True: 1.18k, False: 26]
436
1.21k
        };
437
438
1.21k
        uint64_t trailing = pm_bignum_trailing_zeros(&bignum);
439
1.21k
        twos = trailing > exponent ? 
exponent287
:
(uint32_t) trailing928
;
  Branch (439:16): [True: 287, False: 928]
440
1.21k
        pm_bignum_shift_right(&bignum, twos);
441
442
        /* 5**13 is the largest power of five that fits in a word, so divide by
443
         * it while it divides evenly before dividing by five alone. */
444
1.21k
        while (exponent - fives >= 13 && 
pm_bignum_div_exact(&bignum, powof5[13])26
)
fives += 130
;
  Branch (444:16): [True: 26, False: 1.18k]
  Branch (444:42): [True: 0, False: 26]
445
1.68k
        while (fives < exponent && 
pm_bignum_div_exact(&bignum, 5)1.24k
)
fives++472
;
  Branch (445:16): [True: 1.24k, False: 442]
  Branch (445:36): [True: 472, False: 773]
446
447
1.21k
        if (length <= 2) {
  Branch (447:13): [True: 1.18k, False: 26]
448
1.18k
            *numerator = pm_integer_uint64(pm_bignum_uint64(&bignum));
449
1.18k
        } else {
450
26
            pm_integer_from_bignum(arena, numerator, &bignum, length);
451
26
        }
452
1.21k
    }
453
454
    /* The denominator is what is left of 10**exponent. 2378/1024 is just above
455
     * log2(5), so this capacity never undercounts. */
456
1.29k
    uint32_t remaining_fives = exponent - fives;
457
1.29k
    uint32_t remaining_twos = exponent - twos;
458
1.29k
    uint32_t capacity = (uint32_t) (((uint64_t) remaining_fives * 2378 / 1024 + remaining_twos + 32) / 32);
459
460
1.29k
    pm_bignum_t bignum = {
461
1.29k
        .length = 1,
462
1.29k
        .words = (uint32_t *) pm_arena_alloc(arena, sizeof(uint32_t) * capacity, PRISM_ALIGNOF(uint32_t))
463
1.29k
    };
464
1.29k
    bignum.words[0] = 1;
465
466
1.39k
    for (; remaining_fives >= 13; 
remaining_fives -= 13106
)
pm_bignum_mul_add(&bignum, powof5[13], 0)106
;
  Branch (466:12): [True: 106, False: 1.29k]
467
1.29k
    if (remaining_fives > 0) 
pm_bignum_mul_add(&bignum, powof5[remaining_fives], 0)768
;
  Branch (467:9): [True: 768, False: 524]
468
1.29k
    pm_bignum_shift_left(&bignum, remaining_twos);
469
470
1.29k
    PRISM_ASSERT(bignum.length <= capacity);
  Branch (470:5): [True: 0, False: 1.29k]
  Branch (470:5): [True: 1.29k, False: 0]
471
1.29k
    pm_integer_from_bignum(arena, denominator, &bignum, capacity);
472
1.29k
}
473
474
/**
475
 * Return a view of the magnitude of an integer as a bignum. The view's words
476
 * point into the integer, so it must only be read.
477
 */
478
static pm_bignum_t
479
1.65k
pm_integer_bignum(const pm_integer_t *integer) {
480
1.65k
    uint32_t length;
481
1.65k
    const uint32_t *words = pm_integer_words(integer, &length);
482
1.65k
    return (pm_bignum_t) { .length = length, .words = (uint32_t *) words };
483
1.65k
}
484
485
/**
486
 * Compare two integers. This function returns -1 if the left integer is less
487
 * than the right integer, 0 if they are equal, and 1 if the left integer is
488
 * greater than the right integer.
489
 */
490
int
491
853
pm_integer_compare(const pm_integer_t *left, const pm_integer_t *right) {
492
853
    if (left->negative != right->negative) 
return 26
left->negative26
?
-113
:
113
;
  Branch (492:9): [True: 26, False: 827]
  Branch (492:51): [True: 13, False: 13]
493
827
    int negative = left->negative ? 
-15
:
1822
;
  Branch (493:20): [True: 5, False: 822]
494
495
827
    pm_bignum_t left_bignum = pm_integer_bignum(left);
496
827
    pm_bignum_t right_bignum = pm_integer_bignum(right);
497
827
    return pm_bignum_compare(&left_bignum, &right_bignum) * negative;
498
853
}
499
500
/**
501
 * The number of words of storage needed to convert an integer of length words
502
 * into base 10**9. The integer is below 2**(32 * length), so it needs at most:
503
 *
504
 *     32 * length * log10(2) / 9
505
 *
506
 * words in base 10**9, rounded up. To find 32 * log10(2) / 9, we approximate it
507
 * as 1097/1024, which is slightly greater than the actual value so it does not
508
 * undercount. As in pm_integer_chunks_words, the conversion multiplies the
509
 * high half by a power of two into this storage, which writes the sum of its
510
 * factors' lengths, and each factor's length rounds up on its own, so this is
511
 * one word more than the value needs.
512
 */
513
static PRISM_INLINE uint32_t
514
0
pm_integer_string_words(uint32_t length) {
515
0
    return (uint32_t) ((uint64_t) length * 1097 / 1024 + 2);
516
0
}
517
518
/**
519
 * Convert length words of a bignum into base 10**9. The result's storage must
520
 * have room for pm_integer_string_words(length) words. Up to
521
 * PM_INTEGER_STRING_LEAF words, a copy of the words is divided by 10**9
522
 * until nothing is left, and each remainder is the next word of the result.
523
 * Past it, the words split below the largest power of two less than length, at
524
 * 2**level words, so the value is high * 2**(32 * 2**level) + low with that
525
 * power of two already in base 10**9 in powers[level], and both halves convert
526
 * the same way.
527
 */
528
static void
529
0
pm_integer_string_convert(pm_bignum_t *result, const uint32_t *words, uint32_t length, const pm_bignum_t *powers, pm_bignum_scratch_t *scratch) {
530
    /* The low half of a split can have leading zero words. */
531
0
    while (length > 0 && words[length - 1] == 0) length--;
  Branch (531:12): [True: 0, False: 0]
  Branch (531:26): [True: 0, False: 0]
532
0
    uint32_t *saved = scratch->cursor;
533
534
0
    if (length <= PM_INTEGER_STRING_LEAF) {
  Branch (534:9): [True: 0, False: 0]
535
0
        pm_bignum_t bignum = { .length = length, .words = pm_bignum_scratch_take(scratch, length) };
536
0
        memcpy(bignum.words, words, sizeof(uint32_t) * length);
537
538
0
        result->length = 0;
539
0
        while (bignum.length > 0) result->words[result->length++] = pm_bignum_div(&bignum, PM_BIGNUM_DECIMAL_BASE);
  Branch (539:16): [True: 0, False: 0]
540
0
    } else {
541
0
        uint32_t level = pm_bsrll((uint64_t) length - 1);
542
0
        uint32_t split = (uint32_t) 1 << level;
543
544
0
        pm_bignum_t high = { .length = 0, .words = pm_bignum_scratch_take(scratch, pm_integer_string_words(length - split)) };
545
0
        pm_integer_string_convert(&high, words + split, length - split, powers, scratch);
546
547
0
        PRISM_ASSERT(high.length + powers[level].length <= pm_integer_string_words(length));
  Branch (547:9): [True: 0, False: 0]
  Branch (547:9): [True: 0, False: 0]
548
0
        pm_bignum_decimal_multiply(result, &high, &powers[level], scratch);
549
0
        scratch->cursor = saved;
550
551
0
        pm_bignum_t low = { .length = 0, .words = pm_bignum_scratch_take(scratch, pm_integer_string_words(split)) };
552
0
        pm_integer_string_convert(&low, words, split, powers, scratch);
553
0
        pm_bignum_decimal_add(result, &low);
554
0
    }
555
556
0
    scratch->cursor = saved;
557
0
}
558
559
/**
560
 * Convert the words of an integer of more than PM_INTEGER_STRING_THRESHOLD
561
 * words to a decimal string by divide and conquer. The powers of two that the
562
 * splits need are computed in base 10**9 by repeated squaring, and the integer
563
 * is converted into base 10**9, each word of which is nine digits. Everything
564
 * lives in one block of scratch space from the heap, sized for the worst case:
565
 * the result, the powers, and the halves and products of the deepest chain of
566
 * splits, with Karatsuba's temporaries bounded by 12 times the longer factor's
567
 * length.
568
 */
569
static void
570
0
pm_integer_string_divide(pm_buffer_t *buffer, const uint32_t *words, uint32_t length) {
571
0
    uint32_t capacity = pm_integer_string_words(length);
572
573
    /* The scratch space is about 13 times the number of words, which can
574
     * exceed 32 bits, and on a 32-bit platform its size in bytes can exceed
575
     * size_t. */
576
0
    uint64_t scratch_size = 12 * (uint64_t) capacity + 1024;
577
0
    if (scratch_size > SIZE_MAX / sizeof(uint32_t)) PRISM_OOM();
  Branch (577:9): [True: 0, False: 0]
578
579
0
    uint32_t *allocation = (uint32_t *) xmalloc(sizeof(uint32_t) * (size_t) scratch_size);
580
0
    if (allocation == NULL) PRISM_OOM();
  Branch (580:9): [True: 0, False: 0]
581
0
    pm_bignum_scratch_t scratch = { .cursor = allocation, .end = allocation + (size_t) scratch_size };
582
583
0
    pm_bignum_t result = { .length = 0, .words = pm_bignum_scratch_take(&scratch, capacity) };
584
585
    /* powers[level] is 2**(32 * 2**level) in base 10**9, for every level a
586
     * split uses. */
587
0
    pm_bignum_t powers[64];
588
0
    uint32_t level = 0;
589
0
    powers[level].words = pm_bignum_scratch_take(&scratch, 2);
590
0
    powers[level].words[0] = (uint32_t) (PM_BIGNUM_BINARY_BASE % PM_BIGNUM_DECIMAL_BASE);
591
0
    powers[level].words[1] = (uint32_t) (PM_BIGNUM_BINARY_BASE / PM_BIGNUM_DECIMAL_BASE);
592
0
    powers[level].length = 2;
593
594
0
    for (uint32_t split = 2; split < length; split *= 2) {
  Branch (594:30): [True: 0, False: 0]
595
0
        const pm_bignum_t *previous = &powers[level++];
596
0
        powers[level] = (pm_bignum_t) { .length = 0, .words = pm_bignum_scratch_take(&scratch, 2 * previous->length) };
597
0
        pm_bignum_decimal_multiply(&powers[level], previous, previous, &scratch);
598
0
    }
599
600
0
    pm_integer_string_convert(&result, words, length, powers, &scratch);
601
0
    PRISM_ASSERT(result.length > 0 && result.length < capacity);
  Branch (601:5): [True: 0, False: 0]
  Branch (601:5): [True: 0, False: 0]
  Branch (601:5): [True: 0, False: 0]
  Branch (601:5): [True: 0, False: 0]
602
603
    /* Every word but the most significant is exactly nine digits, padded with
604
     * zeros. */
605
0
    pm_buffer_append_format(buffer, "%" PRIu32, result.words[result.length - 1]);
606
607
0
    for (uint32_t index = result.length - 1; index > 0; index--) {
  Branch (607:46): [True: 0, False: 0]
608
0
        uint32_t word = result.words[index - 1];
609
0
        char digits[9];
610
611
0
        for (size_t digit = 9; digit > 0; digit--) {
  Branch (611:32): [True: 0, False: 0]
612
0
            digits[digit - 1] = (char) ('0' + word % 10);
613
0
            word /= 10;
614
0
        }
615
616
0
        pm_buffer_append_string(buffer, digits, 9);
617
0
    }
618
619
0
    xfree_sized(allocation, sizeof(uint32_t) * (size_t) scratch_size);
620
0
}
621
622
/**
623
 * Convert an integer to a decimal string.
624
 */
625
void
626
122k
pm_integer_string(pm_buffer_t *buffer, const pm_integer_t *integer) {
627
122k
    if (integer->negative) {
  Branch (627:9): [True: 2.42k, False: 119k]
628
2.42k
        pm_buffer_append_byte(buffer, '-');
629
2.42k
    }
630
631
    /* An integer whose words are inline fits in a uint64_t, so it can be
632
     * appended directly. */
633
122k
    if (integer->length <= 2) {
  Branch (633:9): [True: 121k, False: 1.24k]
634
121k
        pm_buffer_append_format(buffer, "%" PRIu64, pm_integer_uint64_value(integer));
635
121k
        return;
636
121k
    }
637
638
1.24k
    if (integer->length > PM_INTEGER_STRING_THRESHOLD) {
  Branch (638:9): [True: 0, False: 1.24k]
639
0
        pm_integer_string_divide(buffer, integer->words.values, integer->length);
640
0
        return;
641
0
    }
642
643
    /* Dividing by 10**9 yields the next nine digits from the remainder, least
644
     * significant first, so the digits are written from the end of the buffer
645
     * toward the front. The division is destructive, so it works on a copy. */
646
1.24k
    const size_t words_size = sizeof(uint32_t) * integer->length;
647
648
    /* A number of n words has at most n * 32 * log10(2) + 1 decimal digits,
649
     * which is at most n * 10 for the three or more words that reach here. */
650
1.24k
    const size_t capacity = (size_t) integer->length * 10;
651
652
    /* The copy of the words and the digits share one allocation, with the
653
     * words first so that they are aligned. */
654
1.24k
    void *allocation = xmalloc(words_size + capacity);
655
1.24k
    if (allocation == NULL) 
PRISM_OOM0
();
  Branch (655:9): [True: 0, False: 1.24k]
656
657
1.24k
    pm_bignum_t bignum = { .length = integer->length, .words = (uint32_t *) allocation };
658
1.24k
    memcpy(bignum.words, integer->words.values, words_size);
659
660
1.24k
    char *digits = (char *) allocation + words_size;
661
1.24k
    size_t offset = capacity;
662
663
6.80k
    while (bignum.length > 0) {
  Branch (663:12): [True: 5.56k, False: 1.24k]
664
5.56k
        uint32_t remainder = pm_bignum_div(&bignum, PM_BIGNUM_DECIMAL_BASE);
665
666
        /* Every chunk but the most significant is exactly nine digits, padded
667
         * with zeros. The most significant chunk is nonzero and stops at its
668
         * leading digit. */
669
49.6k
        for (size_t index = 0; index < 9 && 
(45.2k
bignum.length > 045.2k
||
remainder > 06.42k
);
index++44.1k
) {
  Branch (669:32): [True: 45.2k, False: 4.38k]
  Branch (669:46): [True: 38.8k, False: 6.42k]
  Branch (669:67): [True: 5.25k, False: 1.17k]
670
44.1k
            digits[--offset] = (char) ('0' + remainder % 10);
671
44.1k
            remainder /= 10;
672
44.1k
        }
673
5.56k
    }
674
675
1.24k
    pm_buffer_append_string(buffer, digits + offset, capacity - offset);
676
1.24k
    xfree_sized(allocation, words_size + capacity);
677
1.24k
}