objint.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  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. #include <stdlib.h>
  27. #include <assert.h>
  28. #include <string.h>
  29. #include "py/parsenum.h"
  30. #include "py/smallint.h"
  31. #include "py/objint.h"
  32. #include "py/objstr.h"
  33. #include "py/runtime.h"
  34. #include "py/binary.h"
  35. #if MICROPY_PY_BUILTINS_FLOAT
  36. #include <math.h>
  37. #endif
  38. // This dispatcher function is expected to be independent of the implementation of long int
  39. STATIC 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) {
  40. (void)type_in;
  41. mp_arg_check_num(n_args, n_kw, 0, 2, false);
  42. switch (n_args) {
  43. case 0:
  44. return MP_OBJ_NEW_SMALL_INT(0);
  45. case 1:
  46. if (MP_OBJ_IS_INT(args[0])) {
  47. // already an int (small or long), just return it
  48. return args[0];
  49. } else if (MP_OBJ_IS_STR_OR_BYTES(args[0])) {
  50. // a string, parse it
  51. size_t l;
  52. const char *s = mp_obj_str_get_data(args[0], &l);
  53. return mp_parse_num_integer(s, l, 0, NULL);
  54. #if MICROPY_PY_BUILTINS_FLOAT
  55. } else if (mp_obj_is_float(args[0])) {
  56. return mp_obj_new_int_from_float(mp_obj_float_get(args[0]));
  57. #endif
  58. } else {
  59. // try to convert to small int (eg from bool)
  60. return MP_OBJ_NEW_SMALL_INT(mp_obj_get_int(args[0]));
  61. }
  62. case 2:
  63. default: {
  64. // should be a string, parse it
  65. // TODO proper error checking of argument types
  66. size_t l;
  67. const char *s = mp_obj_str_get_data(args[0], &l);
  68. return mp_parse_num_integer(s, l, mp_obj_get_int(args[1]), NULL);
  69. }
  70. }
  71. }
  72. #if MICROPY_PY_BUILTINS_FLOAT
  73. typedef enum {
  74. MP_FP_CLASS_FIT_SMALLINT,
  75. MP_FP_CLASS_FIT_LONGINT,
  76. MP_FP_CLASS_OVERFLOW
  77. } mp_fp_as_int_class_t;
  78. STATIC mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) {
  79. union {
  80. mp_float_t f;
  81. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  82. uint32_t i;
  83. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  84. uint32_t i[2];
  85. #endif
  86. } u = {val};
  87. uint32_t e;
  88. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  89. e = u.i;
  90. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  91. e = u.i[MP_ENDIANNESS_LITTLE];
  92. #endif
  93. #define MP_FLOAT_SIGN_SHIFT_I32 ((MP_FLOAT_FRAC_BITS + MP_FLOAT_EXP_BITS) % 32)
  94. #define MP_FLOAT_EXP_SHIFT_I32 (MP_FLOAT_FRAC_BITS % 32)
  95. if (e & (1U << MP_FLOAT_SIGN_SHIFT_I32)) {
  96. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  97. e |= u.i[MP_ENDIANNESS_BIG] != 0;
  98. #endif
  99. if ((e & ~(1 << MP_FLOAT_SIGN_SHIFT_I32)) == 0) {
  100. // handle case of -0 (when sign is set but rest of bits are zero)
  101. e = 0;
  102. } else {
  103. e += ((1 << MP_FLOAT_EXP_BITS) - 1) << MP_FLOAT_EXP_SHIFT_I32;
  104. }
  105. } else {
  106. e &= ~((1 << MP_FLOAT_EXP_SHIFT_I32) - 1);
  107. }
  108. // 8 * sizeof(uintptr_t) counts the number of bits for a small int
  109. // TODO provide a way to configure this properly
  110. if (e <= ((8 * sizeof(uintptr_t) + MP_FLOAT_EXP_BIAS - 3) << MP_FLOAT_EXP_SHIFT_I32)) {
  111. return MP_FP_CLASS_FIT_SMALLINT;
  112. }
  113. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
  114. if (e <= (((sizeof(long long) * BITS_PER_BYTE) + MP_FLOAT_EXP_BIAS - 2) << MP_FLOAT_EXP_SHIFT_I32)) {
  115. return MP_FP_CLASS_FIT_LONGINT;
  116. }
  117. #endif
  118. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
  119. return MP_FP_CLASS_FIT_LONGINT;
  120. #else
  121. return MP_FP_CLASS_OVERFLOW;
  122. #endif
  123. }
  124. #undef MP_FLOAT_SIGN_SHIFT_I32
  125. #undef MP_FLOAT_EXP_SHIFT_I32
  126. mp_obj_t mp_obj_new_int_from_float(mp_float_t val) {
  127. int cl = fpclassify(val);
  128. if (cl == FP_INFINITE) {
  129. nlr_raise(mp_obj_new_exception_msg(&mp_type_OverflowError, "can't convert inf to int"));
  130. } else if (cl == FP_NAN) {
  131. mp_raise_ValueError("can't convert NaN to int");
  132. } else {
  133. mp_fp_as_int_class_t icl = mp_classify_fp_as_int(val);
  134. if (icl == MP_FP_CLASS_FIT_SMALLINT) {
  135. return MP_OBJ_NEW_SMALL_INT((mp_int_t)val);
  136. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
  137. } else {
  138. mp_obj_int_t *o = mp_obj_int_new_mpz();
  139. mpz_set_from_float(&o->mpz, val);
  140. return MP_OBJ_FROM_PTR(o);
  141. }
  142. #else
  143. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
  144. } else if (icl == MP_FP_CLASS_FIT_LONGINT) {
  145. return mp_obj_new_int_from_ll((long long)val);
  146. #endif
  147. } else {
  148. mp_raise_ValueError("float too big");
  149. }
  150. #endif
  151. }
  152. }
  153. #endif
  154. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
  155. typedef mp_longint_impl_t fmt_int_t;
  156. typedef unsigned long long fmt_uint_t;
  157. #else
  158. typedef mp_int_t fmt_int_t;
  159. typedef mp_uint_t fmt_uint_t;
  160. #endif
  161. void mp_obj_int_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  162. (void)kind;
  163. // The size of this buffer is rather arbitrary. If it's not large
  164. // enough, a dynamic one will be allocated.
  165. char stack_buf[sizeof(fmt_int_t) * 4];
  166. char *buf = stack_buf;
  167. size_t buf_size = sizeof(stack_buf);
  168. size_t fmt_size;
  169. char *str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size, self_in, 10, NULL, '\0', '\0');
  170. mp_print_str(print, str);
  171. if (buf != stack_buf) {
  172. m_del(char, buf, buf_size);
  173. }
  174. }
  175. STATIC const uint8_t log_base2_floor[] = {
  176. 0, 1, 1, 2,
  177. 2, 2, 2, 3,
  178. 3, 3, 3, 3,
  179. 3, 3, 3, 4,
  180. /* if needed, these are the values for higher bases
  181. 4, 4, 4, 4,
  182. 4, 4, 4, 4,
  183. 4, 4, 4, 4,
  184. 4, 4, 4, 5
  185. */
  186. };
  187. size_t mp_int_format_size(size_t num_bits, int base, const char *prefix, char comma) {
  188. assert(2 <= base && base <= 16);
  189. size_t num_digits = num_bits / log_base2_floor[base - 1] + 1;
  190. size_t num_commas = comma ? num_digits / 3 : 0;
  191. size_t prefix_len = prefix ? strlen(prefix) : 0;
  192. return num_digits + num_commas + prefix_len + 2; // +1 for sign, +1 for null byte
  193. }
  194. // This routine expects you to pass in a buffer and size (in *buf and *buf_size).
  195. // If, for some reason, this buffer is too small, then it will allocate a
  196. // buffer and return the allocated buffer and size in *buf and *buf_size. It
  197. // is the callers responsibility to free this allocated buffer.
  198. //
  199. // The resulting formatted string will be returned from this function and the
  200. // formatted size will be in *fmt_size.
  201. char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
  202. int base, const char *prefix, char base_char, char comma) {
  203. fmt_int_t num;
  204. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
  205. // Only have small ints; get the integer value to format.
  206. num = MP_OBJ_SMALL_INT_VALUE(self_in);
  207. #else
  208. if (MP_OBJ_IS_SMALL_INT(self_in)) {
  209. // A small int; get the integer value to format.
  210. num = MP_OBJ_SMALL_INT_VALUE(self_in);
  211. } else {
  212. assert(MP_OBJ_IS_TYPE(self_in, &mp_type_int));
  213. // Not a small int.
  214. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
  215. const mp_obj_int_t *self = self_in;
  216. // Get the value to format; mp_obj_get_int truncates to mp_int_t.
  217. num = self->val;
  218. #else
  219. // Delegate to the implementation for the long int.
  220. return mp_obj_int_formatted_impl(buf, buf_size, fmt_size, self_in, base, prefix, base_char, comma);
  221. #endif
  222. }
  223. #endif
  224. char sign = '\0';
  225. if (num < 0) {
  226. num = -num;
  227. sign = '-';
  228. }
  229. size_t needed_size = mp_int_format_size(sizeof(fmt_int_t) * 8, base, prefix, comma);
  230. if (needed_size > *buf_size) {
  231. *buf = m_new(char, needed_size);
  232. *buf_size = needed_size;
  233. }
  234. char *str = *buf;
  235. char *b = str + needed_size;
  236. *(--b) = '\0';
  237. char *last_comma = b;
  238. if (num == 0) {
  239. *(--b) = '0';
  240. } else {
  241. do {
  242. // The cast to fmt_uint_t is because num is positive and we want unsigned arithmetic
  243. int c = (fmt_uint_t)num % base;
  244. num = (fmt_uint_t)num / base;
  245. if (c >= 10) {
  246. c += base_char - 10;
  247. } else {
  248. c += '0';
  249. }
  250. *(--b) = c;
  251. if (comma && num != 0 && b > str && (last_comma - b) == 3) {
  252. *(--b) = comma;
  253. last_comma = b;
  254. }
  255. }
  256. while (b > str && num != 0);
  257. }
  258. if (prefix) {
  259. size_t prefix_len = strlen(prefix);
  260. char *p = b - prefix_len;
  261. if (p > str) {
  262. b = p;
  263. while (*prefix) {
  264. *p++ = *prefix++;
  265. }
  266. }
  267. }
  268. if (sign && b > str) {
  269. *(--b) = sign;
  270. }
  271. *fmt_size = *buf + needed_size - b - 1;
  272. return b;
  273. }
  274. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
  275. int mp_obj_int_sign(mp_obj_t self_in) {
  276. mp_int_t val = mp_obj_get_int(self_in);
  277. if (val < 0) {
  278. return -1;
  279. } else if (val > 0) {
  280. return 1;
  281. } else {
  282. return 0;
  283. }
  284. }
  285. // This is called for operations on SMALL_INT that are not handled by mp_unary_op
  286. mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
  287. return MP_OBJ_NULL; // op not supported
  288. }
  289. // This is called for operations on SMALL_INT that are not handled by mp_binary_op
  290. mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
  291. return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in);
  292. }
  293. // This is called only with strings whose value doesn't fit in SMALL_INT
  294. mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base) {
  295. mp_raise_msg(&mp_type_OverflowError, "long int not supported in this build");
  296. return mp_const_none;
  297. }
  298. // This is called when an integer larger than a SMALL_INT is needed (although val might still fit in a SMALL_INT)
  299. mp_obj_t mp_obj_new_int_from_ll(long long val) {
  300. mp_raise_msg(&mp_type_OverflowError, "small int overflow");
  301. return mp_const_none;
  302. }
  303. // This is called when an integer larger than a SMALL_INT is needed (although val might still fit in a SMALL_INT)
  304. mp_obj_t mp_obj_new_int_from_ull(unsigned long long val) {
  305. mp_raise_msg(&mp_type_OverflowError, "small int overflow");
  306. return mp_const_none;
  307. }
  308. mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value) {
  309. // SMALL_INT accepts only signed numbers, so make sure the input
  310. // value fits completely in the small-int positive range.
  311. if ((value & ~MP_SMALL_INT_POSITIVE_MASK) == 0) {
  312. return MP_OBJ_NEW_SMALL_INT(value);
  313. }
  314. mp_raise_msg(&mp_type_OverflowError, "small int overflow");
  315. return mp_const_none;
  316. }
  317. mp_obj_t mp_obj_new_int(mp_int_t value) {
  318. if (MP_SMALL_INT_FITS(value)) {
  319. return MP_OBJ_NEW_SMALL_INT(value);
  320. }
  321. mp_raise_msg(&mp_type_OverflowError, "small int overflow");
  322. return mp_const_none;
  323. }
  324. mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) {
  325. return MP_OBJ_SMALL_INT_VALUE(self_in);
  326. }
  327. mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
  328. return MP_OBJ_SMALL_INT_VALUE(self_in);
  329. }
  330. #endif // MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
  331. // This dispatcher function is expected to be independent of the implementation of long int
  332. // It handles the extra cases for integer-like arithmetic
  333. mp_obj_t mp_obj_int_binary_op_extra_cases(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
  334. if (rhs_in == mp_const_false) {
  335. // false acts as 0
  336. return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(0));
  337. } else if (rhs_in == mp_const_true) {
  338. // true acts as 0
  339. return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(1));
  340. } else if (op == MP_BINARY_OP_MULTIPLY) {
  341. 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)) {
  342. // multiply is commutative for these types, so delegate to them
  343. return mp_binary_op(op, rhs_in, lhs_in);
  344. }
  345. }
  346. return MP_OBJ_NULL; // op not supported
  347. }
  348. // this is a classmethod
  349. STATIC mp_obj_t int_from_bytes(size_t n_args, const mp_obj_t *args) {
  350. // TODO: Support signed param (assumes signed=False at the moment)
  351. (void)n_args;
  352. // get the buffer info
  353. mp_buffer_info_t bufinfo;
  354. mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
  355. const byte* buf = (const byte*)bufinfo.buf;
  356. int delta = 1;
  357. if (args[2] == MP_OBJ_NEW_QSTR(MP_QSTR_little)) {
  358. buf += bufinfo.len - 1;
  359. delta = -1;
  360. }
  361. mp_uint_t value = 0;
  362. size_t len = bufinfo.len;
  363. for (; len--; buf += delta) {
  364. #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
  365. if (value > (MP_SMALL_INT_MAX >> 8)) {
  366. // Result will overflow a small-int so construct a big-int
  367. return mp_obj_int_from_bytes_impl(args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little), bufinfo.len, bufinfo.buf);
  368. }
  369. #endif
  370. value = (value << 8) | *buf;
  371. }
  372. return mp_obj_new_int_from_uint(value);
  373. }
  374. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 3, 4, int_from_bytes);
  375. STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, MP_ROM_PTR(&int_from_bytes_fun_obj));
  376. STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) {
  377. // TODO: Support signed param (assumes signed=False)
  378. (void)n_args;
  379. mp_int_t len = mp_obj_get_int(args[1]);
  380. if (len < 0) {
  381. mp_raise_ValueError(NULL);
  382. }
  383. bool big_endian = args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little);
  384. vstr_t vstr;
  385. vstr_init_len(&vstr, len);
  386. byte *data = (byte*)vstr.buf;
  387. memset(data, 0, len);
  388. #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
  389. if (!MP_OBJ_IS_SMALL_INT(args[0])) {
  390. mp_obj_int_to_bytes_impl(args[0], big_endian, len, data);
  391. } else
  392. #endif
  393. {
  394. mp_int_t val = MP_OBJ_SMALL_INT_VALUE(args[0]);
  395. size_t l = MIN((size_t)len, sizeof(val));
  396. mp_binary_set_int(l, big_endian, data + (big_endian ? (len - l) : 0), val);
  397. }
  398. return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
  399. }
  400. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_to_bytes_obj, 3, 4, int_to_bytes);
  401. STATIC const mp_rom_map_elem_t int_locals_dict_table[] = {
  402. { MP_ROM_QSTR(MP_QSTR_from_bytes), MP_ROM_PTR(&int_from_bytes_obj) },
  403. { MP_ROM_QSTR(MP_QSTR_to_bytes), MP_ROM_PTR(&int_to_bytes_obj) },
  404. };
  405. STATIC MP_DEFINE_CONST_DICT(int_locals_dict, int_locals_dict_table);
  406. const mp_obj_type_t mp_type_int = {
  407. { &mp_type_type },
  408. .name = MP_QSTR_int,
  409. .print = mp_obj_int_print,
  410. .make_new = mp_obj_int_make_new,
  411. .unary_op = mp_obj_int_unary_op,
  412. .binary_op = mp_obj_int_binary_op,
  413. .locals_dict = (mp_obj_dict_t*)&int_locals_dict,
  414. };