Merge pull request #435 from LNP-BP/feat-u256rem

Modulo division operation for Uint128 & Uint256 types
This commit is contained in:
Steven Roose 2020-07-22 10:39:13 +02:00 committed by GitHub
commit 1d5b8dabfe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 0 deletions

View File

@ -40,6 +40,7 @@ fn do_test(data: &[u8]) {
check_eq!(a_native.wrapping_sub(b_native), a - b); check_eq!(a_native.wrapping_sub(b_native), a - b);
if b_native != 0 { if b_native != 0 {
check_eq!(a_native.wrapping_div(b_native), a / b); check_eq!(a_native.wrapping_div(b_native), a / b);
check_eq!(a_native.wrapping_rem(b_native), a % b);
} }
check_eq!(a_native.wrapping_mul(b_native), a * b); check_eq!(a_native.wrapping_mul(b_native), a * b);
check_eq!(a_native & b_native, a & b); check_eq!(a_native & b_native, a & b);

View File

@ -166,6 +166,15 @@ macro_rules! construct_uint {
} }
} }
impl ::std::ops::Rem<$name> for $name {
type Output = $name;
fn rem(self, other: $name) -> $name {
let times = self / other;
self - (times * other)
}
}
impl $crate::util::BitArray for $name { impl $crate::util::BitArray for $name {
#[inline] #[inline]
fn bit(&self, index: usize) -> bool { fn bit(&self, index: usize) -> bool {
@ -479,6 +488,14 @@ mod tests {
Uint256::from_u64(21).unwrap()); Uint256::from_u64(21).unwrap());
let div = mult / Uint256::from_u64(300).unwrap(); let div = mult / Uint256::from_u64(300).unwrap();
assert_eq!(div, Uint256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0])); assert_eq!(div, Uint256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0]));
assert_eq!(Uint256::from_u64(105).unwrap() % Uint256::from_u64(5).unwrap(),
Uint256::from_u64(0).unwrap());
assert_eq!(Uint256::from_u64(35498456).unwrap() % Uint256::from_u64(3435).unwrap(),
Uint256::from_u64(1166).unwrap());
let rem_src = mult * Uint256::from_u64(39842).unwrap() + Uint256::from_u64(9054).unwrap();
assert_eq!(rem_src % Uint256::from_u64(39842).unwrap(),
Uint256::from_u64(9054).unwrap());
// TODO: bit inversion // TODO: bit inversion
} }