Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix BigInt => u128 conversion. #352

Merged
merged 2 commits into from
Aug 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions chain/rust/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,13 +383,13 @@ impl BigInteger {
match *u32_digits {
[] => Some(0),
[a] => Some(u128::from(a)),
[a, b] => Some(u128::from(b) | (u128::from(a) << 32)),
[a, b, c] => Some(u128::from(c) | (u128::from(b) << 32) | (u128::from(a) << 64)),
[a, b] => Some(u128::from(a) | (u128::from(b) << 32)),
[a, b, c] => Some(u128::from(a) | (u128::from(b) << 32) | (u128::from(c) << 64)),
[a, b, c, d] => Some(
u128::from(d)
| (u128::from(c) << 32)
| (u128::from(b) << 64)
| (u128::from(a) << 96),
u128::from(a)
| (u128::from(b) << 32)
| (u128::from(c) << 64)
| (u128::from(d) << 96),
),
_ => None,
}
Expand Down Expand Up @@ -1047,6 +1047,36 @@ mod tests {
assert_eq!(x.to_string(), "18446744073709551615");
}

#[test]
fn bigint_uint_u128_roundtrip() {
let int = 462_164_030_739_157_517;
let x = BigInteger::from_int(&Int::Uint {
value: int,
encoding: None,
});
assert_eq!(x.as_u128(), Some(int as u128))
}

#[test]
fn bigint_uint_u128_roundtrip_min() {
let int = u64::MIN;
let x = BigInteger::from_int(&Int::Uint {
value: int,
encoding: None,
});
assert_eq!(x.as_u128(), Some(int as u128))
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a test case where the bits wouldn't all be uniform (i.e. not all 1's)? Maybe 462_164_030_739_157_517 or something similar could do (anything where the bytes aren't interchangeable) could work. u64::MAX here would have all the byte chunks be 1's / FFFF so wouldn't this test case have passed before the change too?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

#[test]
fn bigint_uint_u128_roundtrip_max() {
let int = u64::MAX;
let x = BigInteger::from_int(&Int::Uint {
value: int,
encoding: None,
});
assert_eq!(x.as_u128(), Some(int as u128))
}

#[test]
fn bigint_uint_u128_min() {
let bytes = [0x00];
Expand Down
Loading