From 703d5acbadd0234aa9c8cbb9aaba7a42aca99fc4 Mon Sep 17 00:00:00 2001 From: Alessandro Gatti Date: Tue, 10 Jun 2025 07:01:17 +0200 Subject: [PATCH] py/misc: Introduce macros to check values' bits size. This commit adds two macros that lets check whether a given value can fit an arbitrary number of bits, either as a signed or as an unsigned number. The native emitter code backends perform a lot of bit size checks to see if a particular code sequence can be emitted instead of a generic one, and each platform backend has its own ad-hoc macros (usually one per bit count and signedness). With these macros there's a single way to perform those checks, plus there's no more chance for off-by-one mask length errors when dealing with signed numbers. Signed-off-by: Alessandro Gatti --- py/misc.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/py/misc.h b/py/misc.h index 1cf582456..5d0893bbd 100644 --- a/py/misc.h +++ b/py/misc.h @@ -395,6 +395,11 @@ static inline uint32_t mp_popcount(uint32_t x) { #endif #endif +#define MP_FIT_UNSIGNED(bits, value) (((value) & (~0U << (bits))) == 0) +#define MP_FIT_SIGNED(bits, value) \ + (MP_FIT_UNSIGNED(((bits) - 1), (value)) || \ + (((value) & (~0U << ((bits) - 1))) == (~0U << ((bits) - 1)))) + // 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) { #ifdef __XC16__