Skip to content

Commit 8759409

Browse files
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
1 parent 1fe5aca commit 8759409

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

vlib/math/big/big_test.v

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,16 @@ fn test_integer_from_string() {
198198
y := big.integer_from_int(int_values[index])
199199
assert x == y
200200
}
201+
202+
imin := big.integer_from_string('-2147483648') or {
203+
panic('Minimum signed 32-bit int test fails.')
204+
}
205+
assert imin.int() == -2147483648
206+
207+
imax := big.integer_from_string('2147483647') or {
208+
panic('Maximum signed 32-bit int test fails.')
209+
}
210+
assert imax.int() == 2147483647
201211
}
202212

203213
fn test_integer_from_powers_of_2() {
@@ -412,7 +422,7 @@ fn test_get_bit() {
412422
'0000000000000000000000000000000000000000010000', '1110010', '0001001']
413423
for value in values {
414424
a := big.integer_from_radix(value, 2) or { panic('Could not read binary') }
415-
bits := []bool{len: value.len, init: value[value.len - 1 - it] == `1`}
425+
bits := []bool{len: value.len, init: value[value.len - 1 - index] == `1`}
416426
for i in 0 .. value.len {
417427
assert a.get_bit(i) == bits[i]
418428
}
@@ -441,7 +451,7 @@ fn test_bit_len() ? {
441451

442452
assert big.one_int.lshift(1239).bit_len() == 1240
443453

444-
mut num := big.integer_from_string('4338476092346017364013796407961305761039463198075691378460917856')?
454+
mut num := big.integer_from_string('4338476092346017364013796407961305761039463198075691378460917856')!
445455
assert num.bit_len() == 212
446456
for num.bit_len() > 0 {
447457
num = num.rshift(8)

vlib/math/big/integer.v

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,11 @@ pub fn (a Integer) int() int {
800800
if a.signum == 0 {
801801
return 0
802802
}
803+
// Check for minimum value int
804+
if a.digits[0] == 2147483648 && a.signum == -1 {
805+
return -2147483648
806+
}
807+
// Rest of the values should be fine
803808
value := int(a.digits[0] & 0x7fffffff)
804809
return value * a.signum
805810
}

0 commit comments

Comments
 (0)