Skip to content

Commit 703d5ac

Browse files
agattidpgeorge
authored andcommitted
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 <a.gatti@frob.it>
1 parent 1eb27e1 commit 703d5ac

1 file changed

Lines changed: 5 additions & 0 deletions

File tree

py/misc.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,11 @@ static inline uint32_t mp_popcount(uint32_t x) {
395395
#endif
396396
#endif
397397

398+
#define MP_FIT_UNSIGNED(bits, value) (((value) & (~0U << (bits))) == 0)
399+
#define MP_FIT_SIGNED(bits, value) \
400+
(MP_FIT_UNSIGNED(((bits) - 1), (value)) || \
401+
(((value) & (~0U << ((bits) - 1))) == (~0U << ((bits) - 1))))
402+
398403
// mp_int_t can be larger than long, i.e. Windows 64-bit, nan-box variants
399404
static inline uint32_t mp_clz_mpi(mp_int_t x) {
400405
#ifdef __XC16__

0 commit comments

Comments
 (0)