1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-22 06:18:07 +00:00

crypto: make bn_format faster

This commit is contained in:
Ondřej Vejpustek 2020-06-01 18:21:24 +02:00
parent 015c294857
commit 9598d17f10

View File

@ -1715,23 +1715,33 @@ size_t bn_format(const bignum256 *amount, const char *prefix, const char *suffix
BN_FORMAT_ADD_OUTPUT_CHAR(suffix[i]) BN_FORMAT_ADD_OUTPUT_CHAR(suffix[i])
// amount //= 10**exponent // amount //= 10**exponent
if (exponent < 0) { for (; exponent < 0; ++exponent) {
for (; exponent < 0; ++exponent) { // if temp == 0, there is no need to divide it by 10 anymore
bn_divmod10(&temp, &digit); if (bn_is_zero(&temp)) {
exponent = 0;
break;
} }
bn_divmod10(&temp, &digit);
} }
// exponent >= 0 && decimals >= 0 // exponent >= 0 && decimals >= 0
bool fractional_part = false; // is fractional-part of amount present bool fractional_part = false; // is fractional-part of amount present
{ // Add fractional-part digits of amount { // Add fractional-part digits of amount
// Add trailing zeroes // Add trailing zeroes
for (; exponent > 0 && decimals > 0; --exponent, --decimals) { unsigned int trailing_zeros = decimals < (unsigned int) exponent ? decimals : (unsigned int) exponent;
if (trailing) { // When casting a negative int to unsigned int, UINT_MAX is added to the int before
BN_FORMAT_ADD_OUTPUT_CHAR('0') // Since exponent >= 0, the value remains unchanged
fractional_part = true; decimals -= trailing_zeros;
} exponent -= trailing_zeros;
if (trailing && trailing_zeros) {
fractional_part = true;
for (; trailing_zeros > 0; --trailing_zeros)
BN_FORMAT_ADD_OUTPUT_CHAR('0')
} }
// exponent == 0 || decimals == 0 // exponent == 0 || decimals == 0
// Add significant digits and leading zeroes // Add significant digits and leading zeroes
@ -1742,6 +1752,11 @@ size_t bn_format(const bignum256 *amount, const char *prefix, const char *suffix
fractional_part = true; fractional_part = true;
BN_FORMAT_ADD_OUTPUT_CHAR('0' + digit) BN_FORMAT_ADD_OUTPUT_CHAR('0' + digit)
} }
else if (bn_is_zero(&temp)) {
// We break since the remaining digits are zeroes and fractional_part == trailing == false
decimals = 0;
break;
}
} }
// decimals == 0 // decimals == 0
} }