1
1
#include "tommath_private.h"
2
2
#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 */
15
5
16
6
/* Compute log_{base}(a) */
17
7
static 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)
68
58
}
69
59
70
60
if (bracket_high == N ) {
71
- ret = ( mp_digit ) high ;
61
+ ret = high ;
72
62
} else {
73
- ret = ( mp_digit ) low ;
63
+ ret = low ;
74
64
}
75
65
76
66
return ret ;
@@ -83,7 +73,7 @@ static mp_digit s_digit_ilogb(mp_digit base, mp_digit n)
83
73
int mp_ilogb (mp_int * a , mp_digit base , mp_int * c )
84
74
{
85
75
int err , cmp ;
86
- mp_digit high , low , mid ;
76
+ unsigned int high , low , mid ;
87
77
mp_int bracket_low , bracket_high , bracket_mid , t , bi_base ;
88
78
mp_digit tmp ;
89
79
@@ -98,8 +88,8 @@ int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
98
88
if (base < 2 ) {
99
89
return MP_VAL ;
100
90
} 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 );
103
93
return err ;
104
94
} else if (a -> used == 1 ) {
105
95
tmp = s_digit_ilogb (base , a -> dp [0 ]);
@@ -150,6 +140,11 @@ int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
150
140
151
141
while ((high - low ) > 1 ) {
152
142
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
+ }
153
148
if ((err = mp_expt_d (& bi_base , (mid - low ), & t )) != MP_OKAY ) {
154
149
goto LBL_ERR ;
155
150
}
@@ -166,17 +161,15 @@ int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
166
161
mp_exch (& bracket_mid , & bracket_low );
167
162
}
168
163
if (cmp == MP_EQ ) {
169
- mp_set (c , mid );
164
+ mp_set_int (c , ( unsigned long ) mid );
170
165
goto LBL_ERR ;
171
166
}
172
167
}
173
168
174
169
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 );
177
171
} else {
178
- mp_set (c , low );
179
- goto LBL_ERR ;
172
+ mp_set_int (c , (unsigned long )low );
180
173
}
181
174
182
175
LBL_ERR :
@@ -187,6 +180,3 @@ int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
187
180
188
181
189
182
#endif
190
- /* ref: $Format:%D$ */
191
- /* git commit: $Format:%H$ */
192
- /* commit time: $Format:%ai$ */
0 commit comments