From 8759409a690f8546413b8c32839801086553bab4 Mon Sep 17 00:00:00 2001 From: Subhomoy Haldar Date: Sun, 26 Mar 2023 06:45:42 +0100 Subject: [PATCH] math.big: fix min i32 value bug (#17775) * attempt big int min value fix * cast value for correct comparison * update edge case * add one more test --- vlib/math/big/big_test.v | 14 ++++++++++++-- vlib/math/big/integer.v | 5 +++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/vlib/math/big/big_test.v b/vlib/math/big/big_test.v index c3bed52cf0..ee211f0056 100644 --- a/vlib/math/big/big_test.v +++ b/vlib/math/big/big_test.v @@ -198,6 +198,16 @@ fn test_integer_from_string() { y := big.integer_from_int(int_values[index]) assert x == y } + + imin := big.integer_from_string('-2147483648') or { + panic('Minimum signed 32-bit int test fails.') + } + assert imin.int() == -2147483648 + + imax := big.integer_from_string('2147483647') or { + panic('Maximum signed 32-bit int test fails.') + } + assert imax.int() == 2147483647 } fn test_integer_from_powers_of_2() { @@ -412,7 +422,7 @@ fn test_get_bit() { '0000000000000000000000000000000000000000010000', '1110010', '0001001'] for value in values { a := big.integer_from_radix(value, 2) or { panic('Could not read binary') } - bits := []bool{len: value.len, init: value[value.len - 1 - it] == `1`} + bits := []bool{len: value.len, init: value[value.len - 1 - index] == `1`} for i in 0 .. value.len { assert a.get_bit(i) == bits[i] } @@ -441,7 +451,7 @@ fn test_bit_len() ? { assert big.one_int.lshift(1239).bit_len() == 1240 - mut num := big.integer_from_string('4338476092346017364013796407961305761039463198075691378460917856')? + mut num := big.integer_from_string('4338476092346017364013796407961305761039463198075691378460917856')! assert num.bit_len() == 212 for num.bit_len() > 0 { num = num.rshift(8) diff --git a/vlib/math/big/integer.v b/vlib/math/big/integer.v index 1b538042ec..5d490b2470 100644 --- a/vlib/math/big/integer.v +++ b/vlib/math/big/integer.v @@ -800,6 +800,11 @@ pub fn (a Integer) int() int { if a.signum == 0 { return 0 } + // Check for minimum value int + if a.digits[0] == 2147483648 && a.signum == -1 { + return -2147483648 + } + // Rest of the values should be fine value := int(a.digits[0] & 0x7fffffff) return value * a.signum }