aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Tools/scripts/long_conv_tables.py
blob: 998a1e0d9b2251e3db2cd31b20e8f75d346f3ff8 (plain) (blame)
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
#!/usr/bin/env python3
#
# Compute tables for longobject.c long_from_non_binary_base().  They are used
# for conversions of strings to integers with a non-binary base.

import math
import textwrap


def format_array(name, values):
    values = [str(v) for v in values]
    values = ', '.join(values)
    result = f'{name} = {{{values}}};'
    result = textwrap.wrap(
        result,
        initial_indent=' ' * 4,
        subsequent_indent=' ' * 8,
    )
    return '\n'.join(result)


def conv_tables(long_bits):
    PyLong_BASE = 1 << long_bits
    log_base_BASE = [0.0] * 37
    convmultmax_base = [0] * 37
    convwidth_base = [0] * 37
    for base in range(2, 37):
        is_binary_base = (base & (base - 1)) == 0
        if is_binary_base:
            continue  # don't need, leave as zero
        convmax = base
        i = 1
        log_base_BASE[base] = math.log(base) / math.log(PyLong_BASE)
        while True:
            next = convmax * base
            if next > PyLong_BASE:
                break
            convmax = next
            i += 1
        convmultmax_base[base] = convmax
        assert i > 0
        convwidth_base[base] = i
    return '\n'.join(
        [
            format_array(
                'static const double log_base_BASE[37]', log_base_BASE
            ),
            format_array(
                'static const int convwidth_base[37]', convwidth_base
            ),
            format_array(
                'static const twodigits convmultmax_base[37]',
                convmultmax_base,
            ),
        ]
    )


def main():
    print(
        f'''\
// Tables are computed by Tools/scripts/long_conv_tables.py
#if PYLONG_BITS_IN_DIGIT == 15
{conv_tables(15)}
#elif PYLONG_BITS_IN_DIGIT == 30
{conv_tables(30)}
#else
    #error "invalid PYLONG_BITS_IN_DIGIT value"
#endif
'''
    )


if __name__ == '__main__':
    main()