aboutsummaryrefslogtreecommitdiff
path: root/src/stdlib/intX.c.h
blob: e6153ac94ef427a14ae14b970d3086115f2c77d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Fixed-width integer type infos and methods
// This file is intended to be used by defining `INTX_C_H__INT_BITS` before including:
//
//    #define INTX_C_H__INT_BITS 32
//    #include "intX.c.h"
//

#include <gc.h>
#include <gmp.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include "../util.h"
#include "datatypes.h"
#include "fail.h"
#include "integers.h"
#include "text.h"
#include "types.h"

#ifndef INTX_C_H__INT_BITS
#define INTX_C_H__INT_BITS 32
#endif

#define CAT_(a, b) a##b
#define CAT(a, b) CAT_(a, b)
#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)

#define INT_T CAT(CAT(int, INTX_C_H__INT_BITS), _t)
#define UINT_T CAT(CAT(uint, INTX_C_H__INT_BITS), _t)
#define OPT_T CAT(CAT(OptionalInt, INTX_C_H__INT_BITS), _t)

#define NAME_STR "Int" STRINGIFY(INTX_C_H__INT_BITS)

#define NAMESPACED(method_name) CAT(CAT(Int, INTX_C_H__INT_BITS), CAT($, method_name))

static Text_t _int64_to_text(int64_t n) {
    if (n == INT64_MIN) return Text("-9223372036854775808");

    char buf[21] = {[20] = 0}; // Big enough for INT64_MIN + '\0'
    char *p = &buf[19];
    bool negative = n < 0;
    if (negative) n = -n; // Safe to do because we checked for INT64_MIN earlier

    do {
        *(p--) = '0' + (n % 10);
        n /= 10;
    } while (n > 0);

    if (negative) *(p--) = '-';

    return Text$from_strn(p + 1, (size_t)(&buf[19] - p));
}

public
void NAMESPACED(serialize)(const void *obj, FILE *out, Table_t *pointers, const TypeInfo_t *info) {
    (void)info, (void)pointers;
#if INTX_C_H__INT_BITS < 32
    if (fwrite(obj, sizeof(INT_T), 1, out) != sizeof(INT_T)) fail_text(Text("Failed to write whole integer"));
#else
    INT_T i = *(INT_T *)obj;
    UINT_T z = (UINT_T)((i << 1L) ^ (i >> (INTX_C_H__INT_BITS - 1L))); // Zigzag encode
    while (z >= 0x80L) {
        if (fputc((uint8_t)(z | 0x80L), out) == EOF) fail_text(Text("Failed to write full integer"));
        z >>= 7L;
    }
    fputc((uint8_t)z, out);
#endif
}

public
void NAMESPACED(deserialize)(FILE *in, void *outval, List_t *pointers, const TypeInfo_t *info) {
    (void)info, (void)pointers;
#if INTX_C_H__INT_BITS < 32
    if (fread(outval, sizeof(INT_T), 1, in) != sizeof(INT_T)) fail_text(Text("Failed to read full integer"));
#else
    UINT_T z = 0;
    for (size_t shift = 0;; shift += 7) {
        int i = fgetc(in);
        if (i == EOF) fail_text(Text("Failed to read whole integer"));
        uint8_t byte = (uint8_t)i;
        z |= ((UINT_T)(byte & 0x7F)) << shift;
        if ((byte & 0x80) == 0) break;
    }
    *(INT_T *)outval = (INT_T)((z >> 1L) ^ -(z & 1L)); // Zigzag decode
#endif
}

#ifdef __TINYC__
#define __builtin_add_overflow(x, y, result)                                                                           \
    ({                                                                                                                 \
        *(result) = (x) + (y);                                                                                         \
        false;                                                                                                         \
    })
#endif

public
Text_t NAMESPACED(as_text)(const void *i, bool colorize, const TypeInfo_t *info) {
    (void)info;
    if (!i) return Text(NAME_STR);
    Text_t text = _int64_to_text((int64_t)(*(INT_T *)i));
    return colorize ? Text$concat(Text("\033[35m"), text, Text("\033[m")) : text;
}
public
Text_t NAMESPACED(value_as_text)(INT_T i) {
    return _int64_to_text((int64_t)i);
}
public
PUREFUNC int32_t NAMESPACED(compare)(const void *x, const void *y, const TypeInfo_t *info) {
    (void)info;
    return (*(INT_T *)x > *(INT_T *)y) - (*(INT_T *)x < *(INT_T *)y);
}
public
PUREFUNC bool NAMESPACED(equal)(const void *x, const void *y, const TypeInfo_t *info) {
    (void)info;
    return *(INT_T *)x == *(INT_T *)y;
}
public
CONSTFUNC bool NAMESPACED(is_between)(const INT_T x, const INT_T low, const INT_T high) {
    return (low <= x && x <= high) || (high <= x && x <= low);
}
public
CONSTFUNC INT_T NAMESPACED(clamped)(INT_T x, INT_T min, INT_T max) {
    return x < min ? min : (x > max ? max : x);
}
public
Text_t NAMESPACED(hex)(INT_T i, Int_t digits_int, bool uppercase, bool prefix) {
    Int_t as_int = Int$from_int64((int64_t)i);
    return Int$hex(as_int, digits_int, uppercase, prefix);
}
public
Text_t NAMESPACED(octal)(INT_T i, Int_t digits_int, bool prefix) {
    Int_t as_int = Int$from_int64((int64_t)i);
    return Int$octal(as_int, digits_int, prefix);
}
public
List_t NAMESPACED(bits)(INT_T x) {
    List_t bit_list = (List_t){.data = GC_MALLOC_ATOMIC(sizeof(bool[8 * sizeof(INT_T)])),
                               .atomic = 1,
                               .stride = sizeof(bool),
                               .length = 8 * sizeof(INT_T)};
    bool *bits = bit_list.data + sizeof(INT_T) * 8;
    for (size_t i = 0; i < 8 * sizeof(INT_T); i++) {
        *(bits--) = x & 1;
        x >>= 1;
    }
    return bit_list;
}
public
bool NAMESPACED(get_bit)(INT_T x, Int_t bit_index) {
    if (Int$compare_value(bit_index, I(1)) < 0) fail("Invalid bit index (expected 1 or higher): ", bit_index);
    if (Int$compare_value(bit_index, Int$from_int64(sizeof(INT_T) * 8)) > 0)
        fail("Bit index is too large! There are only ", (uint64_t)sizeof(INT_T) * 8,
             " bits, but index is: ", bit_index);
    return ((x & (INT_T)(1L << (Int64$from_int(bit_index, true) - 1L))) != 0);
}
typedef struct {
    OPT_T current, last;
    INT_T step;
} NAMESPACED(Range_t);

static OPT_T _next_int(NAMESPACED(Range_t) * info) {
    OPT_T i = info->current;
    if (i.has_value) {
        INT_T next;
        bool overflow = __builtin_add_overflow(i.value, info->step, &next);
        if (overflow || (info->last.has_value && (info->step >= 0 ? next > info->last.value : next < info->last.value)))
            info->current = (OPT_T){.has_value = false};
        else info->current = (OPT_T){.has_value = true, .value = next};
    }
    return i;
}

public
#if INTX_C_H__INT_BITS < 64
CONSTFUNC
#endif
Closure_t NAMESPACED(to)(INT_T first, INT_T last, OPT_T step) {
    NAMESPACED(Range_t) *range = GC_MALLOC(sizeof(NAMESPACED(Range_t)));
    range->current = (OPT_T){.has_value = true, .value = first};
    range->last = (OPT_T){.has_value = true, .value = last};
    range->step = step.has_value ? step.value : (last >= first ? 1 : -1);
    return (Closure_t){.fn = _next_int, .userdata = range};
}

public
#if INTX_C_H__INT_BITS < 64
CONSTFUNC
#endif
Closure_t NAMESPACED(onward)(INT_T first, INT_T step) {
    NAMESPACED(Range_t) *range = GC_MALLOC(sizeof(NAMESPACED(Range_t)));
    range->current = (OPT_T){.has_value = true, .value = first};
    range->last = (OPT_T){.has_value = false};
    range->step = step;
    return (Closure_t){.fn = _next_int, .userdata = range};
}
public
PUREFUNC OPT_T NAMESPACED(parse)(Text_t text, OptionalInt_t base, Text_t *remainder) {
    OptionalInt_t full_int = Int$parse(text, base, remainder);
    if (full_int.small == 0L) return (OPT_T){.has_value = false};
    if (Int$compare_value(full_int, I(NAMESPACED(min))) < 0) {
        return (OPT_T){.has_value = false};
    }
    if (Int$compare_value(full_int, I(NAMESPACED(max))) > 0) {
        return (OPT_T){.has_value = false};
    }
    return (OPT_T){.has_value = true, .value = NAMESPACED(from_int)(full_int, true)};
}

public
PUREFUNC INT_T NAMESPACED(from_num64)(Num_t n, bool truncate) {
    INT_T i = (INT_T)n;
    if (!truncate && unlikely((Num_t)i != n))
        fail_text(
            Text$concat(Text("Could not convert Num to an " NAME_STR " without truncation: "), Num$value_as_text(n)));
    return i;
}

public
PUREFUNC INT_T NAMESPACED(from_num32)(Num32_t n, bool truncate) {
    INT_T i = (INT_T)n;
    if (!truncate && unlikely((Num32_t)i != n))
        fail_text(Text$concat(Text("Could not convert Num32 to an " NAME_STR " without truncation: "),
                              Num32$value_as_text(n)));
    return i;
}

public
PUREFUNC INT_T NAMESPACED(from_int)(Int_t i, bool truncate) {
    if likely (i.small & 1L) {
        INT_T ret = i.small >> 2L;
#if INTX_C_H__INT_BITS < 32
        if (!truncate && unlikely((int64_t)ret != (i.small >> 2L)))
            fail("Integer is too big to fit in an " NAME_STR ": ", i);
#endif
        return ret;
    }
    if (!truncate && unlikely(!mpz_fits_slong_p(i.big))) fail("Integer is too big to fit in an " NAME_STR ": ", i);
    return mpz_get_si(i.big);
}

#if INTX_C_H__INT_BITS < 64
public
PUREFUNC INT_T NAMESPACED(from_int64)(Int64_t i64, bool truncate) {
    INT_T i = (INT_T)i64;
    if (!truncate && unlikely((int64_t)i != i64)) fail("Integer is too big to fit in an " NAME_STR ": ", i64);
    return i;
}
#elif INTX_C_H__INT_BITS > 64
public
CONSTFUNC INT_T NAMESPACED(from_int64)(Int64_t i) { return (INT_T)i; }
#endif

#if INTX_C_H__INT_BITS < 32
public
PUREFUNC INT_T NAMESPACED(from_int32)(Int32_t i32, bool truncate) {
    INT_T i = (INT_T)i32;
    if (!truncate && unlikely((int32_t)i != i32)) fail("Integer is too big to fit in an " NAME_STR ": ", i32);
    return i;
}
#elif INTX_C_H__INT_BITS > 32
public
CONSTFUNC INT_T NAMESPACED(from_int32)(Int32_t i) { return (INT_T)i; }
#endif

#if INTX_C_H__INT_BITS < 16
public
PUREFUNC INT_T NAMESPACED(from_int16)(Int16_t i16, bool truncate) {
    INT_T i = (INT_T)i16;
    if (!truncate && unlikely((int16_t)i != i16)) fail("Integer is too big to fit in an " NAME_STR ": ", i16);
    return i;
}
#elif INTX_C_H__INT_BITS > 16
public
CONSTFUNC INT_T NAMESPACED(from_int16)(Int16_t i) { return (INT_T)i; }
#endif

#if INTX_C_H__INT_BITS > 8
public
CONSTFUNC INT_T NAMESPACED(from_int8)(Int8_t i) { return (INT_T)i; }
#endif

public
CONSTFUNC INT_T NAMESPACED(gcd)(INT_T x, INT_T y) {
    if (x == 0 || y == 0) return 0;
    x = NAMESPACED(abs)(x);
    y = NAMESPACED(abs)(y);
    while (x != y) {
        if (x > y) x -= y;
        else y -= x;
    }
    return x;
}

public
const INT_T NAMESPACED(min) =
#if INTX_C_H__INT_BITS == 64
    INT64_MIN
#elif INTX_C_H__INT_BITS == 32
    INT32_MIN
#elif INTX_C_H__INT_BITS == 16
    INT16_MIN
#elif INTX_C_H__INT_BITS == 8
    INT8_MIN
#else
#error "Unsupported integer bit width"
#endif
    ;

public
const INT_T NAMESPACED(max) =
#if INTX_C_H__INT_BITS == 64
    INT64_MAX
#elif INTX_C_H__INT_BITS == 32
    INT32_MAX
#elif INTX_C_H__INT_BITS == 16
    INT16_MAX
#elif INTX_C_H__INT_BITS == 8
    INT8_MAX
#else
#error "Unsupported integer bit width"
#endif
    ;

public
const TypeInfo_t NAMESPACED(info) = {
    .size = sizeof(INT_T),
    .align = __alignof__(INT_T),
    .metamethods =
        {
            .compare = NAMESPACED(compare),
            .as_text = NAMESPACED(as_text),
            .serialize = NAMESPACED(serialize),
            .deserialize = NAMESPACED(deserialize),
        },
};

#undef CAT_
#undef CAT
#undef STRINGIFY_
#undef STRINGIFY
#undef INT_T
#undef UINT_T
#undef OPT_T
#undef NAME_STR
#undef NAMESPACED
#undef INTX_C_H__INT_BITS