11#include "tommath_private.h"
22#ifdef BN_MP_ILOGB_C
3- /* LibTomMath, multiple-precision integer library -- Tom St Denis
4- *
5- * LibTomMath is a library that provides multiple-precision
6- * integer arithmetic as well as number theoretic functionality.
7- *
8- * The library was designed directly after the MPI library by
9- * Michael Fromberger but has been written from scratch with
10- * additional optimizations in place.
11- *
12- * SPDX-License-Identifier: Unlicense
13- */
14-
3+ /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4+ /* SPDX-License-Identifier: Unlicense */
155
166/* Compute log_{base}(a) */
177static mp_word s_pow (mp_word base , mp_word exponent )
@@ -68,9 +58,9 @@ static mp_digit s_digit_ilogb(mp_digit base, mp_digit n)
6858 }
6959
7060 if (bracket_high == N ) {
71- ret = ( mp_digit ) high ;
61+ ret = high ;
7262 } else {
73- ret = ( mp_digit ) low ;
63+ ret = low ;
7464 }
7565
7666 return ret ;
@@ -83,7 +73,7 @@ static mp_digit s_digit_ilogb(mp_digit base, mp_digit n)
8373int mp_ilogb (mp_int * a , mp_digit base , mp_int * c )
8474{
8575 int err , cmp ;
86- mp_digit high , low , mid ;
76+ unsigned int high , low , mid ;
8777 mp_int bracket_low , bracket_high , bracket_mid , t , bi_base ;
8878 mp_digit tmp ;
8979
@@ -98,8 +88,8 @@ int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
9888 if (base < 2 ) {
9989 return MP_VAL ;
10090 } else if (base == 2 ) {
101- tmp = ( mp_digit ) mp_count_bits (a ) - 1 ;
102- mp_set (c , tmp );
91+ cmp = mp_count_bits (a ) - 1 ;
92+ mp_set_int (c , ( unsigned long ) cmp );
10393 return err ;
10494 } else if (a -> used == 1 ) {
10595 tmp = s_digit_ilogb (base , a -> dp [0 ]);
@@ -150,6 +140,11 @@ int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
150140
151141 while ((high - low ) > 1 ) {
152142 mid = (high + low ) >> 1 ;
143+ /* Difference can be larger then the type behind mp_digit can hold */
144+ if ((mid - low ) > (unsigned int )(MP_MASK )) {
145+ err = MP_VAL ;
146+ goto LBL_ERR ;
147+ }
153148 if ((err = mp_expt_d (& bi_base , (mid - low ), & t )) != MP_OKAY ) {
154149 goto LBL_ERR ;
155150 }
@@ -166,17 +161,15 @@ int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
166161 mp_exch (& bracket_mid , & bracket_low );
167162 }
168163 if (cmp == MP_EQ ) {
169- mp_set (c , mid );
164+ mp_set_int (c , ( unsigned long ) mid );
170165 goto LBL_ERR ;
171166 }
172167 }
173168
174169 if (mp_cmp (& bracket_high , a ) == MP_EQ ) {
175- mp_set (c , high );
176- goto LBL_ERR ;
170+ mp_set_int (c , (unsigned long )high );
177171 } else {
178- mp_set (c , low );
179- goto LBL_ERR ;
172+ mp_set_int (c , (unsigned long )low );
180173 }
181174
182175LBL_ERR :
@@ -187,6 +180,3 @@ int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
187180
188181
189182#endif
190- /* ref: $Format:%D$ */
191- /* git commit: $Format:%H$ */
192- /* commit time: $Format:%ai$ */
0 commit comments