From 6ebb6f3f4e1830d00b44e444600ced8f7f99c088 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Fri, 16 Jan 2026 17:17:18 +0900 Subject: [PATCH] bigint.c: use mpn_cmp() in ucmp() Move mpn_cmp() before ucmp() and simplify ucmp() to use it instead of duplicating the comparison loop. Co-authored-by: Claude --- mrbgems/mruby-bigint/core/bigint.c | 33 ++++++++++++------------------ 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/mrbgems/mruby-bigint/core/bigint.c b/mrbgems/mruby-bigint/core/bigint.c index 56388bbae..8740a6109 100644 --- a/mrbgems/mruby-bigint/core/bigint.c +++ b/mrbgems/mruby-bigint/core/bigint.c @@ -400,6 +400,18 @@ usub(mpz_t *z, mpz_t *y, mpz_t *x) z->sz = digits(z); } +/* Compare two same-length limb arrays: returns <0, 0, or >0 */ +static inline int +mpn_cmp(const mp_limb *ap, const mp_limb *bp, size_t n) +{ + while (n-- > 0) { + if (ap[n] != bp[n]) { + return (ap[n] > bp[n]) ? 1 : -1; + } + } + return 0; +} + /* compare abs(x) and abs(y) */ static int ucmp(mpz_t *y, mpz_t *x) @@ -407,14 +419,7 @@ ucmp(mpz_t *y, mpz_t *x) if (y->sz < x->sz) return -1; if (y->sz > x->sz) return 1; if (x->sz == 0) return 0; - for (size_t i=x->sz-1;; i--) { - mp_limb a = y->p[i]; - mp_limb b = x->p[i]; - if (a > b) return 1; - if (a < b) return -1; - if (i == 0) break; - } - return 0; + return mpn_cmp(y->p, x->p, x->sz); } #define zero_p(x) ((x)->sn == 0) @@ -750,18 +755,6 @@ mpn_addmul_1(mp_limb *rp, const mp_limb *s1p, size_t n, mp_limb limb) #endif } -/* Compare two same-length limb arrays: returns <0, 0, or >0 */ -static inline int -mpn_cmp(const mp_limb *ap, const mp_limb *bp, size_t n) -{ - while (n-- > 0) { - if (ap[n] != bp[n]) { - return (ap[n] > bp[n]) ? 1 : -1; - } - } - return 0; -} - /* w = u * v (optimized schoolbook using mpn_addmul_1) */ static void mpz_mul_basic(mpz_ctx_t *ctx, mpz_t *ww, mpz_t *u, mpz_t *v)