blob: 87d8a27852d348e32b5052c115b1b961aa0079c7 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
Alexander Steffen55f33242017-06-30 09:22:17 +02002 * This file is part of the MicroPython project, http://micropython.org/
Damien George04b91472014-05-03 23:27:38 +01003 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
Damien George660aef62014-04-02 12:22:07 +010027#include <stdlib.h>
Damien George45b43c22014-01-05 01:50:45 +000028#include <assert.h>
Dave Hylandsc4029e52014-04-07 11:19:51 -070029#include <string.h>
Damien George45b43c22014-01-05 01:50:45 +000030
Damien George51dfcb42015-01-01 20:27:54 +000031#include "py/parsenum.h"
32#include "py/smallint.h"
33#include "py/objint.h"
34#include "py/objstr.h"
Damien George51dfcb42015-01-01 20:27:54 +000035#include "py/runtime.h"
Damien George271d18e2015-04-25 23:16:39 +010036#include "py/binary.h"
Paul Sokolovsky48b35722014-01-12 17:30:48 +020037
Damien Georgefb510b32014-06-01 13:32:54 +010038#if MICROPY_PY_BUILTINS_FLOAT
Damien George6433bd92014-03-30 23:13:16 +010039#include <math.h>
40#endif
41
Damien Georgee8208a72014-04-04 15:08:23 +010042// This dispatcher function is expected to be independent of the implementation of long int
Angus Grattondecf8e62024-02-27 15:32:29 +110043static mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
Damien Georgeff8dd3f2015-01-20 12:47:20 +000044 (void)type_in;
Damien Georgeee7a8802014-05-11 18:37:21 +010045 mp_arg_check_num(n_args, n_kw, 0, 2, false);
Damien George20006db2014-01-18 14:10:48 +000046
Damien George45b43c22014-01-05 01:50:45 +000047 switch (n_args) {
48 case 0:
49 return MP_OBJ_NEW_SMALL_INT(0);
50
Damien George48ffd652023-05-25 10:57:08 +100051 case 1: {
Damien George69dd0132023-05-23 18:02:32 +100052 mp_buffer_info_t bufinfo;
Damien George48ffd652023-05-25 10:57:08 +100053 mp_obj_t o = mp_unary_op(MP_UNARY_OP_INT_MAYBE, args[0]);
54 if (o != MP_OBJ_NULL) {
55 return o;
Damien George69dd0132023-05-23 18:02:32 +100056 } else if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
57 // a textual representation, parse it
Jeff Epler13b13d12024-01-03 19:31:35 -060058 return mp_parse_num_integer(bufinfo.buf, bufinfo.len, 10, NULL);
Damien George69661f32020-02-27 15:36:53 +110059 #if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +010060 } else if (mp_obj_is_float(args[0])) {
Paul Sokolovsky12033df2014-12-30 00:22:10 +020061 return mp_obj_new_int_from_float(mp_obj_float_get(args[0]));
Damien George69661f32020-02-27 15:36:53 +110062 #endif
Damien George5573f9f2014-01-15 22:58:39 +000063 } else {
Damien George48ffd652023-05-25 10:57:08 +100064 mp_raise_TypeError_int_conversion(args[0]);
Damien George5573f9f2014-01-15 22:58:39 +000065 }
Damien George48ffd652023-05-25 10:57:08 +100066 }
Damien George45b43c22014-01-05 01:50:45 +000067
xybc178ea42014-01-14 21:39:05 +080068 case 2:
Damien Georgeee7a8802014-05-11 18:37:21 +010069 default: {
Damien George5573f9f2014-01-15 22:58:39 +000070 // should be a string, parse it
Damien George6b341072017-03-25 19:48:18 +110071 size_t l;
Damien George698ec212014-02-08 18:17:23 +000072 const char *s = mp_obj_str_get_data(args[0], &l);
Damien George7d414a12015-02-08 01:57:40 +000073 return mp_parse_num_integer(s, l, mp_obj_get_int(args[1]), NULL);
Damien George5fa93b62014-01-22 14:35:10 +000074 }
Damien George45b43c22014-01-05 01:50:45 +000075 }
76}
77
David Steinbergca377b12015-01-13 15:21:17 +000078#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgefc245d12017-04-04 16:45:49 +100079
80typedef enum {
81 MP_FP_CLASS_FIT_SMALLINT,
82 MP_FP_CLASS_FIT_LONGINT,
83 MP_FP_CLASS_OVERFLOW
84} mp_fp_as_int_class_t;
85
Angus Grattondecf8e62024-02-27 15:32:29 +110086static mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) {
David Steinbergca377b12015-01-13 15:21:17 +000087 union {
88 mp_float_t f;
Damien George69661f32020-02-27 15:36:53 +110089 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
David Steinbergca377b12015-01-13 15:21:17 +000090 uint32_t i;
Damien George69661f32020-02-27 15:36:53 +110091 #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
David Steinbergca377b12015-01-13 15:21:17 +000092 uint32_t i[2];
Damien George69661f32020-02-27 15:36:53 +110093 #endif
David Steinbergca377b12015-01-13 15:21:17 +000094 } u = {val};
95
96 uint32_t e;
Damien George69661f32020-02-27 15:36:53 +110097 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
David Steinbergca377b12015-01-13 15:21:17 +000098 e = u.i;
Damien George69661f32020-02-27 15:36:53 +110099 #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
David Steinbergca377b12015-01-13 15:21:17 +0000100 e = u.i[MP_ENDIANNESS_LITTLE];
Damien George69661f32020-02-27 15:36:53 +1100101 #endif
David Steinbergca377b12015-01-13 15:21:17 +0000102#define MP_FLOAT_SIGN_SHIFT_I32 ((MP_FLOAT_FRAC_BITS + MP_FLOAT_EXP_BITS) % 32)
103#define MP_FLOAT_EXP_SHIFT_I32 (MP_FLOAT_FRAC_BITS % 32)
104
Tom Collins145796f2017-06-30 16:23:29 -0700105 if (e & (1U << MP_FLOAT_SIGN_SHIFT_I32)) {
Damien George69661f32020-02-27 15:36:53 +1100106 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
David Steinbergca377b12015-01-13 15:21:17 +0000107 e |= u.i[MP_ENDIANNESS_BIG] != 0;
Damien George69661f32020-02-27 15:36:53 +1100108 #endif
Jeff Epler413f34c2021-06-08 07:45:56 -0500109 if ((e & ~(1U << MP_FLOAT_SIGN_SHIFT_I32)) == 0) {
Damien Georgec0735192017-03-23 23:51:35 +1100110 // handle case of -0 (when sign is set but rest of bits are zero)
111 e = 0;
112 } else {
Jeff Epler413f34c2021-06-08 07:45:56 -0500113 e += ((1U << MP_FLOAT_EXP_BITS) - 1) << MP_FLOAT_EXP_SHIFT_I32;
Damien Georgec0735192017-03-23 23:51:35 +1100114 }
David Steinbergca377b12015-01-13 15:21:17 +0000115 } else {
Jeff Epler413f34c2021-06-08 07:45:56 -0500116 e &= ~((1U << MP_FLOAT_EXP_SHIFT_I32) - 1);
David Steinbergca377b12015-01-13 15:21:17 +0000117 }
Damien Georgeda3dffa2016-01-08 17:57:30 +0000118 // 8 * sizeof(uintptr_t) counts the number of bits for a small int
119 // TODO provide a way to configure this properly
120 if (e <= ((8 * sizeof(uintptr_t) + MP_FLOAT_EXP_BIAS - 3) << MP_FLOAT_EXP_SHIFT_I32)) {
David Steinbergca377b12015-01-13 15:21:17 +0000121 return MP_FP_CLASS_FIT_SMALLINT;
122 }
Damien George69661f32020-02-27 15:36:53 +1100123 #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
Damien George7e956fa2021-02-04 15:32:59 +1100124 if (e <= (((sizeof(long long) * MP_BITS_PER_BYTE) + MP_FLOAT_EXP_BIAS - 2) << MP_FLOAT_EXP_SHIFT_I32)) {
David Steinbergca377b12015-01-13 15:21:17 +0000125 return MP_FP_CLASS_FIT_LONGINT;
126 }
Damien George69661f32020-02-27 15:36:53 +1100127 #endif
128 #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
David Steinbergca377b12015-01-13 15:21:17 +0000129 return MP_FP_CLASS_FIT_LONGINT;
Damien George69661f32020-02-27 15:36:53 +1100130 #else
David Steinbergca377b12015-01-13 15:21:17 +0000131 return MP_FP_CLASS_OVERFLOW;
Damien George69661f32020-02-27 15:36:53 +1100132 #endif
David Steinbergca377b12015-01-13 15:21:17 +0000133}
134#undef MP_FLOAT_SIGN_SHIFT_I32
135#undef MP_FLOAT_EXP_SHIFT_I32
Damien Georgefc245d12017-04-04 16:45:49 +1000136
137mp_obj_t mp_obj_new_int_from_float(mp_float_t val) {
stijnf31f9a82020-04-06 10:44:48 +0200138 mp_float_union_t u = {val};
139 // IEEE-754: if biased exponent is all 1 bits...
140 if (u.p.exp == ((1 << MP_FLOAT_EXP_BITS) - 1)) {
141 // ...then number is Inf (positive or negative) if fraction is 0, else NaN.
142 if (u.p.frc == 0) {
143 mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("can't convert inf to int"));
144 } else {
145 mp_raise_ValueError(MP_ERROR_TEXT("can't convert NaN to int"));
146 }
Damien Georgefc245d12017-04-04 16:45:49 +1000147 } else {
148 mp_fp_as_int_class_t icl = mp_classify_fp_as_int(val);
149 if (icl == MP_FP_CLASS_FIT_SMALLINT) {
150 return MP_OBJ_NEW_SMALL_INT((mp_int_t)val);
151 #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
152 } else {
153 mp_obj_int_t *o = mp_obj_int_new_mpz();
154 mpz_set_from_float(&o->mpz, val);
155 return MP_OBJ_FROM_PTR(o);
156 }
157 #else
158 #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
159 } else if (icl == MP_FP_CLASS_FIT_LONGINT) {
160 return mp_obj_new_int_from_ll((long long)val);
161 #endif
162 } else {
Jim Mussareddef76fe2020-03-02 22:35:22 +1100163 mp_raise_ValueError(MP_ERROR_TEXT("float too big"));
Damien Georgefc245d12017-04-04 16:45:49 +1000164 }
165 #endif
166 }
167}
168
David Steinbergca377b12015-01-13 15:21:17 +0000169#endif
170
Damien Georged1ae6ae2017-03-14 14:54:20 +1100171#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
172typedef mp_longint_impl_t fmt_int_t;
Damien Georgee31fbd92017-04-11 15:18:35 +1000173typedef unsigned long long fmt_uint_t;
Damien Georged1ae6ae2017-03-14 14:54:20 +1100174#else
175typedef mp_int_t fmt_int_t;
Damien Georgee31fbd92017-04-11 15:18:35 +1000176typedef mp_uint_t fmt_uint_t;
Damien Georged1ae6ae2017-03-14 14:54:20 +1100177#endif
178
Damien George7f9d1d62015-04-09 23:56:15 +0100179void mp_obj_int_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
Damien Georgeff8dd3f2015-01-20 12:47:20 +0000180 (void)kind;
Dave Hylandsc4029e52014-04-07 11:19:51 -0700181 // The size of this buffer is rather arbitrary. If it's not large
182 // enough, a dynamic one will be allocated.
Damien Georged1ae6ae2017-03-14 14:54:20 +1100183 char stack_buf[sizeof(fmt_int_t) * 4];
Dave Hylandsc4029e52014-04-07 11:19:51 -0700184 char *buf = stack_buf;
Damien George6dff3df2016-10-11 13:20:11 +1100185 size_t buf_size = sizeof(stack_buf);
186 size_t fmt_size;
Dave Hylandsc4029e52014-04-07 11:19:51 -0700187
188 char *str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size, self_in, 10, NULL, '\0', '\0');
Damien George7f9d1d62015-04-09 23:56:15 +0100189 mp_print_str(print, str);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700190
191 if (buf != stack_buf) {
Damien George4d77e1a2015-02-27 09:34:51 +0000192 m_del(char, buf, buf_size);
Damien George5fa93b62014-01-22 14:35:10 +0000193 }
Damien George45b43c22014-01-05 01:50:45 +0000194}
Paul Sokolovsky48b35722014-01-12 17:30:48 +0200195
Angus Grattondecf8e62024-02-27 15:32:29 +1100196static const uint8_t log_base2_floor[] = {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700197 0, 1, 1, 2,
198 2, 2, 2, 3,
199 3, 3, 3, 3,
200 3, 3, 3, 4,
Damien Georgeea6a9582016-12-28 12:46:20 +1100201 /* if needed, these are the values for higher bases
Dave Hylandsc4029e52014-04-07 11:19:51 -0700202 4, 4, 4, 4,
203 4, 4, 4, 4,
204 4, 4, 4, 4,
205 4, 4, 4, 5
Damien Georgeea6a9582016-12-28 12:46:20 +1100206 */
Dave Hylandsc4029e52014-04-07 11:19:51 -0700207};
208
Damien George8bb7d952016-10-11 13:11:32 +1100209size_t mp_int_format_size(size_t num_bits, int base, const char *prefix, char comma) {
Damien Georgeea6a9582016-12-28 12:46:20 +1100210 assert(2 <= base && base <= 16);
211 size_t num_digits = num_bits / log_base2_floor[base - 1] + 1;
Jeff Epler90324912024-01-25 09:09:06 -0600212 size_t num_commas = comma ? (base == 10 ? num_digits / 3 : num_digits / 4): 0;
Damien George8bb7d952016-10-11 13:11:32 +1100213 size_t prefix_len = prefix ? strlen(prefix) : 0;
Dave Hylandsc4029e52014-04-07 11:19:51 -0700214 return num_digits + num_commas + prefix_len + 2; // +1 for sign, +1 for null byte
215}
216
Paul Sokolovskyd72bc272014-06-06 23:08:37 +0300217// This routine expects you to pass in a buffer and size (in *buf and *buf_size).
Dave Hylandsc4029e52014-04-07 11:19:51 -0700218// If, for some reason, this buffer is too small, then it will allocate a
219// buffer and return the allocated buffer and size in *buf and *buf_size. It
220// is the callers responsibility to free this allocated buffer.
221//
222// The resulting formatted string will be returned from this function and the
223// formatted size will be in *fmt_size.
Damien George6dff3df2016-10-11 13:20:11 +1100224char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
Damien George69661f32020-02-27 15:36:53 +1100225 int base, const char *prefix, char base_char, char comma) {
Damien George88d7bba2014-04-08 23:30:46 +0100226 fmt_int_t num;
Damien George9884a2c2018-03-02 11:01:24 +1100227 #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
228 // Only have small ints; get the integer value to format.
229 num = MP_OBJ_SMALL_INT_VALUE(self_in);
230 #else
Damien Georgeeee1e882019-01-30 18:49:52 +1100231 if (mp_obj_is_small_int(self_in)) {
Damien George88d7bba2014-04-08 23:30:46 +0100232 // A small int; get the integer value to format.
Damien Georgef66df1e2017-04-11 15:16:09 +1000233 num = MP_OBJ_SMALL_INT_VALUE(self_in);
Damien George9884a2c2018-03-02 11:01:24 +1100234 } else {
Yonatan Goldschmidt2a6ba472020-01-22 13:34:19 +0100235 assert(mp_obj_is_exact_type(self_in, &mp_type_int));
Damien George88d7bba2014-04-08 23:30:46 +0100236 // Not a small int.
Damien George9884a2c2018-03-02 11:01:24 +1100237 #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
Damien George503d6112014-05-28 14:07:21 +0100238 const mp_obj_int_t *self = self_in;
Damien George40f3c022014-07-03 13:25:24 +0100239 // Get the value to format; mp_obj_get_int truncates to mp_int_t.
Damien George88d7bba2014-04-08 23:30:46 +0100240 num = self->val;
Damien George9884a2c2018-03-02 11:01:24 +1100241 #else
Damien George88d7bba2014-04-08 23:30:46 +0100242 // Delegate to the implementation for the long int.
243 return mp_obj_int_formatted_impl(buf, buf_size, fmt_size, self_in, base, prefix, base_char, comma);
Damien George9884a2c2018-03-02 11:01:24 +1100244 #endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700245 }
Damien George9884a2c2018-03-02 11:01:24 +1100246 #endif
Damien George88d7bba2014-04-08 23:30:46 +0100247
Dave Hylandsc4029e52014-04-07 11:19:51 -0700248 char sign = '\0';
249 if (num < 0) {
250 num = -num;
251 sign = '-';
252 }
253
Jeff Epler90324912024-01-25 09:09:06 -0600254 int n_comma = (base == 10) ? 3 : 4;
Damien George6dff3df2016-10-11 13:20:11 +1100255 size_t needed_size = mp_int_format_size(sizeof(fmt_int_t) * 8, base, prefix, comma);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700256 if (needed_size > *buf_size) {
257 *buf = m_new(char, needed_size);
258 *buf_size = needed_size;
259 }
260 char *str = *buf;
261
262 char *b = str + needed_size;
263 *(--b) = '\0';
264 char *last_comma = b;
265
266 if (num == 0) {
267 *(--b) = '0';
268 } else {
269 do {
Damien Georgee31fbd92017-04-11 15:18:35 +1000270 // The cast to fmt_uint_t is because num is positive and we want unsigned arithmetic
271 int c = (fmt_uint_t)num % base;
272 num = (fmt_uint_t)num / base;
Dave Hylandsc4029e52014-04-07 11:19:51 -0700273 if (c >= 10) {
274 c += base_char - 10;
275 } else {
276 c += '0';
277 }
278 *(--b) = c;
Jeff Epler90324912024-01-25 09:09:06 -0600279 if (comma && num != 0 && b > str && (last_comma - b) == n_comma) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700280 *(--b) = comma;
281 last_comma = b;
282 }
283 }
284 while (b > str && num != 0);
285 }
286 if (prefix) {
287 size_t prefix_len = strlen(prefix);
288 char *p = b - prefix_len;
289 if (p > str) {
290 b = p;
291 while (*prefix) {
292 *p++ = *prefix++;
293 }
294 }
295 }
296 if (sign && b > str) {
297 *(--b) = sign;
298 }
299 *fmt_size = *buf + needed_size - b - 1;
300
301 return b;
302}
303
Damien George88d7bba2014-04-08 23:30:46 +0100304#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
305
Damien Georged6b31e42016-01-07 14:29:12 +0000306int mp_obj_int_sign(mp_obj_t self_in) {
307 mp_int_t val = mp_obj_get_int(self_in);
308 if (val < 0) {
309 return -1;
310 } else if (val > 0) {
311 return 1;
312 } else {
313 return 0;
314 }
Dave Hylandsc4029e52014-04-07 11:19:51 -0700315}
Dave Hylandsc4029e52014-04-07 11:19:51 -0700316
Damien George660aef62014-04-02 12:22:07 +0100317// This is called for operations on SMALL_INT that are not handled by mp_unary_op
Damien George58321dd2017-08-29 13:04:01 +1000318mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
Damien George6ac5dce2014-05-21 19:42:43 +0100319 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky9b00dad2014-01-27 09:05:50 +0200320}
321
Damien George660aef62014-04-02 12:22:07 +0100322// This is called for operations on SMALL_INT that are not handled by mp_binary_op
Damien George58321dd2017-08-29 13:04:01 +1000323mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien Georgee8208a72014-04-04 15:08:23 +0100324 return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in);
Paul Sokolovsky48b35722014-01-12 17:30:48 +0200325}
326
327// This is called only with strings whose value doesn't fit in SMALL_INT
Damien Georgeda36f522017-02-16 16:41:43 +1100328mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base) {
Jim Mussareddef76fe2020-03-02 22:35:22 +1100329 mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("long int not supported in this build"));
Damien George23005372014-01-13 19:39:01 +0000330 return mp_const_none;
Paul Sokolovsky48b35722014-01-12 17:30:48 +0200331}
332
Damien George9d68e9c2014-03-12 15:38:15 +0000333// This is called when an integer larger than a SMALL_INT is needed (although val might still fit in a SMALL_INT)
334mp_obj_t mp_obj_new_int_from_ll(long long val) {
Jim Mussareddef76fe2020-03-02 22:35:22 +1100335 mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow"));
Damien George9d68e9c2014-03-12 15:38:15 +0000336 return mp_const_none;
337}
338
Damien George95307432014-09-10 22:10:33 +0100339// This is called when an integer larger than a SMALL_INT is needed (although val might still fit in a SMALL_INT)
340mp_obj_t mp_obj_new_int_from_ull(unsigned long long val) {
Jim Mussareddef76fe2020-03-02 22:35:22 +1100341 mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow"));
Damien George95307432014-09-10 22:10:33 +0100342 return mp_const_none;
343}
344
Damien George40f3c022014-07-03 13:25:24 +0100345mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value) {
Damien George9ae51252016-03-10 21:52:56 +0000346 // SMALL_INT accepts only signed numbers, so make sure the input
347 // value fits completely in the small-int positive range.
348 if ((value & ~MP_SMALL_INT_POSITIVE_MASK) == 0) {
Paul Sokolovsky48b35722014-01-12 17:30:48 +0200349 return MP_OBJ_NEW_SMALL_INT(value);
350 }
Jim Mussareddef76fe2020-03-02 22:35:22 +1100351 mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow"));
Damien George23005372014-01-13 19:39:01 +0000352 return mp_const_none;
Paul Sokolovsky48b35722014-01-12 17:30:48 +0200353}
354
Damien George40f3c022014-07-03 13:25:24 +0100355mp_obj_t mp_obj_new_int(mp_int_t value) {
Damien Georged1e355e2014-05-28 14:51:12 +0100356 if (MP_SMALL_INT_FITS(value)) {
Paul Sokolovsky48b35722014-01-12 17:30:48 +0200357 return MP_OBJ_NEW_SMALL_INT(value);
358 }
Jim Mussareddef76fe2020-03-02 22:35:22 +1100359 mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow"));
Damien George23005372014-01-13 19:39:01 +0000360 return mp_const_none;
Paul Sokolovsky48b35722014-01-12 17:30:48 +0200361}
Paul Sokolovskyd26b3792014-01-18 16:07:16 +0200362
Damien Georgebe6d8be2014-12-05 23:13:52 +0000363mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) {
Paul Sokolovskyd26b3792014-01-18 16:07:16 +0200364 return MP_OBJ_SMALL_INT_VALUE(self_in);
365}
366
Damien George40f3c022014-07-03 13:25:24 +0100367mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
Paul Sokolovskyd26b3792014-01-18 16:07:16 +0200368 return MP_OBJ_SMALL_INT_VALUE(self_in);
369}
370
Damien George5fa93b62014-01-22 14:35:10 +0000371#endif // MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
372
Damien Georgee8208a72014-04-04 15:08:23 +0100373// This dispatcher function is expected to be independent of the implementation of long int
374// It handles the extra cases for integer-like arithmetic
Damien George58321dd2017-08-29 13:04:01 +1000375mp_obj_t mp_obj_int_binary_op_extra_cases(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien Georgee8208a72014-04-04 15:08:23 +0100376 if (rhs_in == mp_const_false) {
377 // false acts as 0
378 return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(0));
379 } else if (rhs_in == mp_const_true) {
380 // true acts as 0
381 return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(1));
382 } else if (op == MP_BINARY_OP_MULTIPLY) {
Damien Georgeeee1e882019-01-30 18:49:52 +1100383 if (mp_obj_is_str_or_bytes(rhs_in) || mp_obj_is_type(rhs_in, &mp_type_tuple) || mp_obj_is_type(rhs_in, &mp_type_list)) {
Damien Georgee8208a72014-04-04 15:08:23 +0100384 // multiply is commutative for these types, so delegate to them
385 return mp_binary_op(op, rhs_in, lhs_in);
386 }
387 }
Damien George6ac5dce2014-05-21 19:42:43 +0100388 return MP_OBJ_NULL; // op not supported
Damien Georgee8208a72014-04-04 15:08:23 +0100389}
390
Damien George5213eb32014-04-13 12:24:13 +0100391// this is a classmethod
Angus Grattondecf8e62024-02-27 15:32:29 +1100392static mp_obj_t int_from_bytes(size_t n_args, const mp_obj_t *args) {
Damien George5213eb32014-04-13 12:24:13 +0100393 // TODO: Support signed param (assumes signed=False at the moment)
394
395 // get the buffer info
Damien George57a4b4f2014-04-18 22:29:21 +0100396 mp_buffer_info_t bufinfo;
Damien Georgeb11b85a2014-04-18 22:59:24 +0100397 mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
Damien George5213eb32014-04-13 12:24:13 +0100398
Damien George69661f32020-02-27 15:36:53 +1100399 const byte *buf = (const byte *)bufinfo.buf;
Damien George58bb73e2017-05-05 21:42:39 +1000400 int delta = 1;
Amirreza Hamzavicb7e9902024-04-28 16:46:58 +0330401 bool big_endian = n_args < 3 || args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little);
402 if (!big_endian) {
Damien George58bb73e2017-05-05 21:42:39 +1000403 buf += bufinfo.len - 1;
404 delta = -1;
Paul Sokolovskybec7bfb2017-01-21 20:14:18 +0300405 }
Damien George58bb73e2017-05-05 21:42:39 +1000406
407 mp_uint_t value = 0;
408 size_t len = bufinfo.len;
409 for (; len--; buf += delta) {
410 #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
411 if (value > (MP_SMALL_INT_MAX >> 8)) {
412 // Result will overflow a small-int so construct a big-int
Amirreza Hamzavicb7e9902024-04-28 16:46:58 +0330413 return mp_obj_int_from_bytes_impl(big_endian, bufinfo.len, bufinfo.buf);
Damien George58bb73e2017-05-05 21:42:39 +1000414 }
415 #endif
416 value = (value << 8) | *buf;
417 }
418 return mp_obj_new_int_from_uint(value);
Paul Sokolovskya985b452014-04-09 00:40:58 +0300419}
420
Amirreza Hamzavicb7e9902024-04-28 16:46:58 +0330421static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 2, 4, int_from_bytes);
Angus Grattondecf8e62024-02-27 15:32:29 +1100422static MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, MP_ROM_PTR(&int_from_bytes_fun_obj));
Paul Sokolovskya985b452014-04-09 00:40:58 +0300423
Angus Grattondecf8e62024-02-27 15:32:29 +1100424static mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) {
Angus Gratton908ab1c2023-11-29 11:23:16 +1100425 // TODO: Support signed (currently behaves as if signed=(val < 0))
Angus Gratton908ab1c2023-11-29 11:23:16 +1100426 bool overflow;
Damien Georgefcdb2392014-10-06 13:45:34 +0000427
Amirreza Hamzavi0b432b32024-04-30 19:10:25 +0330428 mp_int_t dlen = n_args < 2 ? 1 : mp_obj_get_int(args[1]);
Angus Gratton908ab1c2023-11-29 11:23:16 +1100429 if (dlen < 0) {
Damien Georgee269cab2017-06-15 14:21:02 +1000430 mp_raise_ValueError(NULL);
431 }
Amirreza Hamzavi80c5e762024-04-28 15:56:57 +0330432 bool big_endian = n_args < 3 || args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little);
Damien Georgefcdb2392014-10-06 13:45:34 +0000433
Damien George05005f62015-01-21 22:48:37 +0000434 vstr_t vstr;
Angus Gratton908ab1c2023-11-29 11:23:16 +1100435 vstr_init_len(&vstr, dlen);
Damien George69661f32020-02-27 15:36:53 +1100436 byte *data = (byte *)vstr.buf;
Damien Georgefcdb2392014-10-06 13:45:34 +0000437
Damien George271d18e2015-04-25 23:16:39 +0100438 #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
Damien Georgeeee1e882019-01-30 18:49:52 +1100439 if (!mp_obj_is_small_int(args[0])) {
Angus Gratton908ab1c2023-11-29 11:23:16 +1100440 overflow = !mp_obj_int_to_bytes_impl(args[0], big_endian, dlen, data);
Damien George271d18e2015-04-25 23:16:39 +0100441 } else
442 #endif
443 {
444 mp_int_t val = MP_OBJ_SMALL_INT_VALUE(args[0]);
Angus Gratton908ab1c2023-11-29 11:23:16 +1100445 int slen = 0; // Number of bytes to represent val
446
447 // This logic has a twin in objint_longlong.c
448 if (val > 0) {
449 slen = (sizeof(mp_int_t) * 8 - mp_clz_mpi(val) + 7) / 8;
450 } else if (val < -1) {
451 slen = (sizeof(mp_int_t) * 8 - mp_clz_mpi(~val) + 8) / 8;
452 } else {
453 // clz of 0 is defined, so 0 and -1 map to 0 and 1
454 slen = -val;
455 }
456
457 if (slen <= dlen) {
458 memset(data, val < 0 ? 0xFF : 0x00, dlen);
459 mp_binary_set_int(slen, big_endian, data + (big_endian ? (dlen - slen) : 0), val);
460 overflow = false;
461 } else {
462 overflow = true;
463 }
464 }
465
466 if (overflow) {
467 mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("buffer too small"));
Damien Georgefcdb2392014-10-06 13:45:34 +0000468 }
469
Jim Mussared8a0ee5a2022-08-22 17:08:05 +1000470 return mp_obj_new_bytes_from_vstr(&vstr);
Paul Sokolovskya985b452014-04-09 00:40:58 +0300471}
Amirreza Hamzavi0b432b32024-04-30 19:10:25 +0330472static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_to_bytes_obj, 1, 4, int_to_bytes);
Paul Sokolovskya985b452014-04-09 00:40:58 +0300473
Angus Grattondecf8e62024-02-27 15:32:29 +1100474static const mp_rom_map_elem_t int_locals_dict_table[] = {
Damien Georgecbf76742015-11-27 13:38:15 +0000475 { MP_ROM_QSTR(MP_QSTR_from_bytes), MP_ROM_PTR(&int_from_bytes_obj) },
476 { MP_ROM_QSTR(MP_QSTR_to_bytes), MP_ROM_PTR(&int_to_bytes_obj) },
Paul Sokolovskya985b452014-04-09 00:40:58 +0300477};
478
Angus Grattondecf8e62024-02-27 15:32:29 +1100479static MP_DEFINE_CONST_DICT(int_locals_dict, int_locals_dict_table);
Paul Sokolovskya985b452014-04-09 00:40:58 +0300480
Jim Mussared662b9762021-07-14 14:38:38 +1000481MP_DEFINE_CONST_OBJ_TYPE(
482 mp_type_int,
483 MP_QSTR_int,
484 MP_TYPE_FLAG_NONE,
Jim Mussared94beeab2022-09-17 00:31:23 +1000485 make_new, mp_obj_int_make_new,
Jim Mussared662b9762021-07-14 14:38:38 +1000486 print, mp_obj_int_print,
487 unary_op, mp_obj_int_unary_op,
488 binary_op, mp_obj_int_binary_op,
Jim Mussared9dce8272022-06-24 16:27:46 +1000489 locals_dict, &int_locals_dict
Jim Mussared662b9762021-07-14 14:38:38 +1000490 );