From ed177794348df5903dbc79ba947dbbba04e2da61 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Wed, 18 May 2022 08:29:08 +0300 Subject: [PATCH] math.big: fix Integer.bit_len() when there are no digits in the number --- vlib/math/big/big_test.v | 11 +++++++---- vlib/math/big/integer.v | 4 +++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/vlib/math/big/big_test.v b/vlib/math/big/big_test.v index d60fca4d55..0915378aef 100644 --- a/vlib/math/big/big_test.v +++ b/vlib/math/big/big_test.v @@ -433,7 +433,7 @@ fn test_set_bit() { assert a == b } -fn test_bit_len() { +fn test_bit_len() ? { assert big.zero_int.bit_len() == 0 assert big.one_int.bit_len() == 1 @@ -441,7 +441,10 @@ fn test_bit_len() { assert big.one_int.lshift(1239).bit_len() == 1240 - assert big.integer_from_string('4338476092346017364013796407961305761039463198075691378460917856') or { - panic('Could not read from decimal') - }.bit_len() == 212 + mut num := big.integer_from_string('4338476092346017364013796407961305761039463198075691378460917856')? + assert num.bit_len() == 212 + for num.bit_len() > 0 { + num = num.rshift(8) + assert true + } } diff --git a/vlib/math/big/integer.v b/vlib/math/big/integer.v index 8ae09b432f..653d1e58a3 100644 --- a/vlib/math/big/integer.v +++ b/vlib/math/big/integer.v @@ -960,6 +960,8 @@ pub fn (x Integer) bit_len() int { if x.signum == 0 { return 0 } - + if x.digits.len == 0 { + return 0 + } return x.digits.len * 32 - bits.leading_zeros_32(x.digits.last()) }