objint.c 14.7 KB
Newer Older
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
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

27
#include <stdlib.h>
Damien George's avatar
Damien George committed
28
#include <assert.h>
29
#include <string.h>
Damien George's avatar
Damien George committed
30

31
32
33
34
35
36
37
#include "py/nlr.h"
#include "py/parsenum.h"
#include "py/smallint.h"
#include "py/objint.h"
#include "py/objstr.h"
#include "py/runtime0.h"
#include "py/runtime.h"
38

39
#if MICROPY_PY_BUILTINS_FLOAT
40
41
42
#include <math.h>
#endif

43
// This dispatcher function is expected to be independent of the implementation of long int
44
STATIC mp_obj_t mp_obj_int_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
45
    (void)type_in;
46
    mp_arg_check_num(n_args, n_kw, 0, 2, false);
47

Damien George's avatar
Damien George committed
48
49
50
51
52
    switch (n_args) {
        case 0:
            return MP_OBJ_NEW_SMALL_INT(0);

        case 1:
53
54
55
            if (MP_OBJ_IS_INT(args[0])) {
                // already an int (small or long), just return it
                return args[0];
Dave Hylands's avatar
Dave Hylands committed
56
            } else if (MP_OBJ_IS_STR_OR_BYTES(args[0])) {
57
                // a string, parse it
58
                mp_uint_t l;
59
                const char *s = mp_obj_str_get_data(args[0], &l);
60
                return mp_parse_num_integer(s, l, 0, NULL);
61
#if MICROPY_PY_BUILTINS_FLOAT
62
            } else if (MP_OBJ_IS_TYPE(args[0], &mp_type_float)) {
63
                return mp_obj_new_int_from_float(mp_obj_float_get(args[0]));
64
#endif
65
            } else {
66
                // try to convert to small int (eg from bool)
67
68
                return MP_OBJ_NEW_SMALL_INT(mp_obj_get_int(args[0]));
            }
Damien George's avatar
Damien George committed
69

xyb's avatar
xyb committed
70
        case 2:
71
        default: {
72
73
            // should be a string, parse it
            // TODO proper error checking of argument types
74
            mp_uint_t l;
75
            const char *s = mp_obj_str_get_data(args[0], &l);
76
            return mp_parse_num_integer(s, l, mp_obj_get_int(args[1]), NULL);
77
        }
Damien George's avatar
Damien George committed
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
#if MICROPY_PY_BUILTINS_FLOAT
mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) {
    union {
        mp_float_t f;
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
        uint32_t i;
#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
        uint32_t i[2];
#endif
    } u = {val};

    uint32_t e;
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
    e = u.i;
#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
    e = u.i[MP_ENDIANNESS_LITTLE];
#endif
#define MP_FLOAT_SIGN_SHIFT_I32 ((MP_FLOAT_FRAC_BITS + MP_FLOAT_EXP_BITS) % 32)
#define MP_FLOAT_EXP_SHIFT_I32 (MP_FLOAT_FRAC_BITS % 32)

    if (e & (1 << MP_FLOAT_SIGN_SHIFT_I32)) {
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
        e |= u.i[MP_ENDIANNESS_BIG] != 0;
#endif
        e += ((1 << MP_FLOAT_EXP_BITS) - 1) << MP_FLOAT_EXP_SHIFT_I32;
    } else {
        e &= ~((1 << MP_FLOAT_EXP_SHIFT_I32) - 1);
    }
    if (e <= ((BITS_PER_WORD + MP_FLOAT_EXP_BIAS - 3) << MP_FLOAT_EXP_SHIFT_I32)) {
        return MP_FP_CLASS_FIT_SMALLINT;
    }
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
    if (e <= (((sizeof(long long) * BITS_PER_BYTE) + MP_FLOAT_EXP_BIAS - 2) << MP_FLOAT_EXP_SHIFT_I32)) {
        return MP_FP_CLASS_FIT_LONGINT;
    }
#endif
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
    return MP_FP_CLASS_FIT_LONGINT;
#else
    return MP_FP_CLASS_OVERFLOW;
#endif
}
#undef MP_FLOAT_SIGN_SHIFT_I32
#undef MP_FLOAT_EXP_SHIFT_I32
#endif

127
void mp_obj_int_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
128
    (void)kind;
129
130
    // The size of this buffer is rather arbitrary. If it's not large
    // enough, a dynamic one will be allocated.
131
    char stack_buf[sizeof(mp_int_t) * 4];
132
    char *buf = stack_buf;
133
134
    mp_uint_t buf_size = sizeof(stack_buf);
    mp_uint_t fmt_size;
135
136
137
138
139

    char *str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size, self_in, 10, NULL, '\0', '\0');
    print(env, "%s", str);

    if (buf != stack_buf) {
140
        m_del(char, buf, buf_size);
141
142
143
144
    }
}

#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
145
typedef mp_longint_impl_t fmt_int_t;
146
#else
147
typedef mp_int_t fmt_int_t;
148
149
#endif

150
STATIC const uint8_t log_base2_floor[] = {
151
152
153
154
155
156
157
158
159
160
161
    0,
    0, 1, 1, 2,
    2, 2, 2, 3,
    3, 3, 3, 3,
    3, 3, 3, 4,
    4, 4, 4, 4,
    4, 4, 4, 4,
    4, 4, 4, 4,
    4, 4, 4, 5
};

162
STATIC uint int_as_str_size_formatted(uint base, const char *prefix, char comma) {
163
164
165
166
167
168
169
170
171
172
    if (base < 2 || base > 32) {
        return 0;
    }

    uint num_digits = sizeof(fmt_int_t) * 8 / log_base2_floor[base] + 1;
    uint num_commas = comma ? num_digits / 3: 0;
    uint prefix_len = prefix ? strlen(prefix) : 0;
    return num_digits + num_commas + prefix_len + 2; // +1 for sign, +1 for null byte
}

173
// This routine expects you to pass in a buffer and size (in *buf and *buf_size).
174
175
176
177
178
179
// If, for some reason, this buffer is too small, then it will allocate a
// buffer and return the allocated buffer and size in *buf and *buf_size. It
// is the callers responsibility to free this allocated buffer.
//
// The resulting formatted string will be returned from this function and the
// formatted size will be in *fmt_size.
180
char *mp_obj_int_formatted(char **buf, mp_uint_t *buf_size, mp_uint_t *fmt_size, mp_const_obj_t self_in,
181
                           int base, const char *prefix, char base_char, char comma) {
182
    fmt_int_t num;
183
184
185
186
187
188
    if (MP_OBJ_IS_SMALL_INT(self_in)) {
        // A small int; get the integer value to format.
        num = mp_obj_get_int(self_in);
#if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
    } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_int)) {
        // Not a small int.
189
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
190
        const mp_obj_int_t *self = self_in;
191
        // Get the value to format; mp_obj_get_int truncates to mp_int_t.
192
        num = self->val;
193
194
195
#else
        // Delegate to the implementation for the long int.
        return mp_obj_int_formatted_impl(buf, buf_size, fmt_size, self_in, base, prefix, base_char, comma);
196
#endif
197
198
199
#endif
    } else {
        // Not an int.
200
        **buf = '\0';
201
202
        *fmt_size = 0;
        return *buf;
203
    }
204

205
206
207
208
209
210
211
212
213
214
    char sign = '\0';
    if (num < 0) {
        num = -num;
        sign = '-';
    }

    uint needed_size = int_as_str_size_formatted(base, prefix, comma);
    if (needed_size > *buf_size) {
        *buf = m_new(char, needed_size);
        *buf_size = needed_size;
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
    char *str = *buf;

    char *b = str + needed_size;
    *(--b) = '\0';
    char *last_comma = b;

    if (num == 0) {
        *(--b) = '0';
    } else {
        do {
            int c = num % base;
            num /= base;
            if (c >= 10) {
                c += base_char - 10;
            } else {
                c += '0';
            }
            *(--b) = c;
            if (comma && num != 0 && b > str && (last_comma - b) == 3) {
                *(--b) = comma;
                last_comma = b;
            }
        }
        while (b > str && num != 0);
    }
    if (prefix) {
        size_t prefix_len = strlen(prefix);
        char *p = b - prefix_len;
        if (p > str) {
            b = p;
            while (*prefix) {
                *p++ = *prefix++;
            }
        }
    }
    if (sign && b > str) {
        *(--b) = sign;
    }
    *fmt_size = *buf + needed_size - b - 1;

    return b;
257
258
}

259
260
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE

Damien George's avatar
Damien George committed
261
262
263
264
mp_int_t mp_obj_int_hash(mp_obj_t self_in) {
    return MP_OBJ_SMALL_INT_VALUE(self_in);
}

265
266
267
268
bool mp_obj_int_is_positive(mp_obj_t self_in) {
    return mp_obj_get_int(self_in) >= 0;
}

269
270
271
272
273
274
275
276
277
278
// This must handle int and bool types, and must raise a
// TypeError if the argument is not integral
mp_obj_t mp_obj_int_abs(mp_obj_t self_in) {
    mp_int_t val = mp_obj_get_int(self_in);
    if (val < 0) {
        val = -val;
    }
    return MP_OBJ_NEW_SMALL_INT(val);
}

279
// This is called for operations on SMALL_INT that are not handled by mp_unary_op
280
mp_obj_t mp_obj_int_unary_op(mp_uint_t op, mp_obj_t o_in) {
281
    return MP_OBJ_NULL; // op not supported
282
283
}

284
// This is called for operations on SMALL_INT that are not handled by mp_binary_op
285
mp_obj_t mp_obj_int_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
286
    return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in);
287
288
289
}

// This is called only with strings whose value doesn't fit in SMALL_INT
290
mp_obj_t mp_obj_new_int_from_str_len(const char **str, mp_uint_t len, bool neg, mp_uint_t base) {
291
    nlr_raise(mp_obj_new_exception_msg(&mp_type_OverflowError, "long int not supported in this build"));
292
    return mp_const_none;
293
294
}

295
296
// This is called when an integer larger than a SMALL_INT is needed (although val might still fit in a SMALL_INT)
mp_obj_t mp_obj_new_int_from_ll(long long val) {
297
    nlr_raise(mp_obj_new_exception_msg(&mp_type_OverflowError, "small int overflow"));
298
299
300
    return mp_const_none;
}

301
302
303
304
305
306
// This is called when an integer larger than a SMALL_INT is needed (although val might still fit in a SMALL_INT)
mp_obj_t mp_obj_new_int_from_ull(unsigned long long val) {
    nlr_raise(mp_obj_new_exception_msg(&mp_type_OverflowError, "small int overflow"));
    return mp_const_none;
}

307
mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value) {
308
309
310
311
312
    // SMALL_INT accepts only signed numbers, of one bit less size
    // then word size, which totals 2 bits less for unsigned numbers.
    if ((value & (WORD_MSBIT_HIGH | (WORD_MSBIT_HIGH >> 1))) == 0) {
        return MP_OBJ_NEW_SMALL_INT(value);
    }
313
    nlr_raise(mp_obj_new_exception_msg(&mp_type_OverflowError, "small int overflow"));
314
    return mp_const_none;
315
316
}

317
318
#if MICROPY_PY_BUILTINS_FLOAT
mp_obj_t mp_obj_new_int_from_float(mp_float_t val) {
319
320
321
322
323
324
325
326
327
328
329
330
331
    int cl = fpclassify(val);
    if (cl == FP_INFINITE) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OverflowError, "can't convert inf to int"));
    } else if (cl == FP_NAN) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "can't convert NaN to int"));
    } else {
        mp_fp_as_int_class_t icl = mp_classify_fp_as_int(val);
        if (icl == MP_FP_CLASS_FIT_SMALLINT) {
            return MP_OBJ_NEW_SMALL_INT((mp_int_t)val);
        } else {
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "float too big"));
        }
    }
332
333
334
}
#endif

335
mp_obj_t mp_obj_new_int(mp_int_t value) {
336
    if (MP_SMALL_INT_FITS(value)) {
337
338
        return MP_OBJ_NEW_SMALL_INT(value);
    }
339
    nlr_raise(mp_obj_new_exception_msg(&mp_type_OverflowError, "small int overflow"));
340
    return mp_const_none;
Damien George's avatar
Damien George committed
341
}
342

343
mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) {
344
345
346
    return MP_OBJ_SMALL_INT_VALUE(self_in);
}

347
mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
348
349
350
    return MP_OBJ_SMALL_INT_VALUE(self_in);
}

351
#if MICROPY_PY_BUILTINS_FLOAT
352
353
354
355
356
mp_float_t mp_obj_int_as_float(mp_obj_t self_in) {
    return MP_OBJ_SMALL_INT_VALUE(self_in);
}
#endif

357
358
#endif // MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE

359
360
// This dispatcher function is expected to be independent of the implementation of long int
// It handles the extra cases for integer-like arithmetic
361
mp_obj_t mp_obj_int_binary_op_extra_cases(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
362
363
364
365
366
367
368
    if (rhs_in == mp_const_false) {
        // false acts as 0
        return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(0));
    } else if (rhs_in == mp_const_true) {
        // true acts as 0
        return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(1));
    } else if (op == MP_BINARY_OP_MULTIPLY) {
369
        if (MP_OBJ_IS_STR(rhs_in) || MP_OBJ_IS_TYPE(rhs_in, &mp_type_bytes) || MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(rhs_in, &mp_type_list)) {
370
371
372
373
            // multiply is commutative for these types, so delegate to them
            return mp_binary_op(op, rhs_in, lhs_in);
        }
    }
374
    return MP_OBJ_NULL; // op not supported
375
376
}

377
// this is a classmethod
378
STATIC mp_obj_t int_from_bytes(mp_uint_t n_args, const mp_obj_t *args) {
379
380
381
    // TODO: Support long ints
    // TODO: Support byteorder param (assumes 'little' at the moment)
    // TODO: Support signed param (assumes signed=False at the moment)
382
    (void)n_args;
383
384

    // get the buffer info
385
    mp_buffer_info_t bufinfo;
386
    mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
387

388
    // convert the bytes to an integer
389
    mp_uint_t value = 0;
stijn's avatar
stijn committed
390
    for (const byte* buf = (const byte*)bufinfo.buf + bufinfo.len - 1; buf >= (byte*)bufinfo.buf; buf--) {
391
        value = (value << 8) | *buf;
392
393
394
    }

    return mp_obj_new_int_from_uint(value);
395
396
}

397
398
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 2, 3, int_from_bytes);
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, (const mp_obj_t)&int_from_bytes_fun_obj);
399

400
STATIC mp_obj_t int_to_bytes(mp_uint_t n_args, const mp_obj_t *args) {
401
402
403
    // TODO: Support long ints
    // TODO: Support byteorder param (assumes 'little')
    // TODO: Support signed param (assumes signed=False)
404
    (void)n_args;
405

406
    mp_int_t val = mp_obj_int_get_checked(args[0]);
407
    mp_uint_t len = MP_OBJ_SMALL_INT_VALUE(args[1]);
408

409
410
411
    vstr_t vstr;
    vstr_init_len(&vstr, len);
    byte *data = (byte*)vstr.buf;
412
    memset(data, 0, len);
413
414
415
416
417
418
419
420
421
422

    if (MP_ENDIANNESS_LITTLE) {
        memcpy(data, &val, len < sizeof(mp_int_t) ? len : sizeof(mp_int_t));
    } else {
        while (len--) {
            *data++ = val;
            val >>= 8;
        }
    }

423
    return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
424
425
426
427
428
429
430
431
432
433
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_to_bytes_obj, 2, 4, int_to_bytes);

STATIC const mp_map_elem_t int_locals_dict_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR_from_bytes), (mp_obj_t)&int_from_bytes_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_to_bytes), (mp_obj_t)&int_to_bytes_obj },
};

STATIC MP_DEFINE_CONST_DICT(int_locals_dict, int_locals_dict_table);

434
const mp_obj_type_t mp_type_int = {
435
    { &mp_type_type },
436
    .name = MP_QSTR_int,
437
438
439
440
    .print = mp_obj_int_print,
    .make_new = mp_obj_int_make_new,
    .unary_op = mp_obj_int_unary_op,
    .binary_op = mp_obj_int_binary_op,
441
    .locals_dict = (mp_obj_t)&int_locals_dict,
442
};