objint.c 15 KB

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