math.big: fix big.from_string #7313 (#7351)

pull/7353/head
LilEnvy 2020-12-15 17:23:02 -08:00 committed by GitHub
parent 52f908839e
commit 665e6cc957
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 1 deletions

View File

@ -93,7 +93,13 @@ pub fn from_u64(u u64) Number {
}
// Converts a hex string to big.Number.
pub fn from_string(s string) Number {
pub fn from_string(input string) Number {
mut s := input.trim_prefix('0x')
if s.len == 0 {
s = '0'
}
padding := '0'.repeat((8 - s.len % 8) % 8)
s = padding + s
n := Number{}
C.bignum_from_string(&n, s.str, s.len)
return n

View File

@ -77,6 +77,19 @@ fn test_mod() {
assert (big.from_u64(7) % big.from_u64(5)).int() == 2
}
fn test_from_str() {
assert big.from_string('').hexstr() == '0'
assert big.from_string('1').hexstr() == '1'
assert big.from_string('0').hexstr() == '0'
assert big.from_string('0x123').hexstr() == '123'
for i in 1 .. 33 {
input := 'e'.repeat(i)
out := big.from_string(input).hexstr()
assert input == out
}
assert big.from_string('0').hexstr() == '0'
}
fn test_str() {
assert big.from_u64(255).str() == '255'
assert big.from_u64(127).str() == '127'