summaryrefslogtreecommitdiff
path: root/py/misc.h
diff options
context:
space:
mode:
authorAngus Gratton <angus@redyak.com.au>2023-11-29 11:23:16 +1100
committerDamien George <damien@micropython.org>2024-06-24 14:07:00 +1000
commit908ab1ceca15ee6fd0ef82ca4cba770a3ec41894 (patch)
tree94d7e1d9e191d277f9500a310d8247ca528cfc37 /py/misc.h
parentd933210d960a6f9337e85753e9568619bbfd54ec (diff)
py/objint: Fix int.to_bytes() buffer size checks.
Fixes and improvements to `int.to_bytes()` are: - No longer overflows if byte size is 0 (closes #13041). - Raises OverflowError in any case where number won't fit into byte length (now matches CPython, previously MicroPython would return a truncated bytes object). - Document that `micropython int.to_bytes()` doesn't implement the optional signed kwarg, but will behave as if `signed=True` when the integer is negative (this is the current behaviour). Add tests for this also. Requires changes for small ints, MPZ large ints, and "long long" large ints. Adds a new set of unit tests for ints between 32 and 64 bits to increase coverage of "long long" large ints, which are otherwise untested. Tested on unix port (64 bit small ints, MPZ long ints) and Zephyr STM32WB board (32 bit small ints, long long large ints). This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton <angus@redyak.com.au>
Diffstat (limited to 'py/misc.h')
-rw-r--r--py/misc.h33
1 files changed, 33 insertions, 0 deletions
diff --git a/py/misc.h b/py/misc.h
index 9f8a8c1e1..cf1810d4e 100644
--- a/py/misc.h
+++ b/py/misc.h
@@ -343,13 +343,46 @@ static uint32_t mp_clz(uint32_t x) {
return _BitScanReverse(&lz, x) ? (sizeof(x) * 8 - 1) - lz : 0;
}
+static uint32_t mp_clzl(unsigned long x) {
+ unsigned long lz = 0;
+ return _BitScanReverse(&lz, x) ? (sizeof(x) * 8 - 1) - lz : 0;
+}
+
+#ifdef _WIN64
+static uint32_t mp_clzll(unsigned long long x) {
+ unsigned long lz = 0;
+ return _BitScanReverse64(&lz, x) ? (sizeof(x) * 8 - 1) - lz : 0;
+}
+#else
+// Microsoft don't ship _BitScanReverse64 on Win32, so emulate it
+static uint32_t mp_clzll(unsigned long long x) {
+ unsigned long h = x >> 32;
+ return h ? mp_clzl(h) : (mp_clzl(x) + 32);
+}
+#endif
+
static uint32_t mp_ctz(uint32_t x) {
unsigned long tz = 0;
return _BitScanForward(&tz, x) ? tz : 0;
}
#else
#define mp_clz(x) __builtin_clz(x)
+#define mp_clzl(x) __builtin_clzl(x)
+#define mp_clzll(x) __builtin_clzll(x)
#define mp_ctz(x) __builtin_ctz(x)
#endif
+// mp_int_t can be larger than long, i.e. Windows 64-bit, nan-box variants
+static inline uint32_t mp_clz_mpi(mp_int_t x) {
+ MP_STATIC_ASSERT(sizeof(mp_int_t) == sizeof(long long)
+ || sizeof(mp_int_t) == sizeof(long));
+
+ // ugly, but should compile to single intrinsic unless O0 is set
+ if (sizeof(mp_int_t) == sizeof(long)) {
+ return mp_clzl(x);
+ } else {
+ return mp_clzll(x);
+ }
+}
+
#endif // MICROPY_INCLUDED_PY_MISC_H