Skip to content

Commit

Permalink
Uint: Add support for bit and,or,xor assign traits (#690)
Browse files Browse the repository at this point in the history
* Uint: Add support for bit and,or,xor assign traits

* Add tests for bit-assign

* satisfy rustfmt
  • Loading branch information
halo3mic authored Nov 7, 2022
1 parent 0373dec commit 82b2147
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
18 changes: 18 additions & 0 deletions uint/src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1508,6 +1508,12 @@ macro_rules! construct_uint {
}
}

impl $crate::core_::ops::BitAndAssign<$name> for $name {
fn bitand_assign(&mut self, rhs: $name) {
*self = *self & rhs;
}
}

impl $crate::core_::ops::BitXor<$name> for $name {
type Output = $name;

Expand All @@ -1523,6 +1529,12 @@ macro_rules! construct_uint {
}
}

impl $crate::core_::ops::BitXorAssign<$name> for $name {
fn bitxor_assign(&mut self, rhs: $name) {
*self = *self ^ rhs;
}
}

impl $crate::core_::ops::BitOr<$name> for $name {
type Output = $name;

Expand All @@ -1538,6 +1550,12 @@ macro_rules! construct_uint {
}
}

impl $crate::core_::ops::BitOrAssign<$name> for $name {
fn bitor_assign(&mut self, rhs: $name) {
*self = *self | rhs;
}
}

impl $crate::core_::ops::Not for $name {
type Output = $name;

Expand Down
41 changes: 41 additions & 0 deletions uint/tests/uint_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1151,6 +1151,47 @@ fn trailing_zeros() {
assert_eq!(U256::from("0000000000000000000000000000000000000000000000000000000000000000").trailing_zeros(), 256);
}

#[test]
fn bit_assign() {
fn check(a: U256, b: U256) {
// and
{
let mut x = a;
x &= b;
assert_eq!(x, a & b);
}
// or
{
let mut x = a;
x |= b;
assert_eq!(x, a | b);
}
// xor
{
let mut x = a;
x ^= b;
assert_eq!(x, a ^ b);
}
// shr
{
let mut x = a;
x >>= b;
assert_eq!(x, a >> b);
}
// shl
{
let mut x = a;
x <<= b;
assert_eq!(x, a << b);
}
}

check(U256::from(9), U256::from(999999));
check(U256::from(0), U256::from(0));
check(U256::from(23432), U256::from(u32::MAX));
check(U256::MAX, U256::zero());
}

#[cfg(feature = "quickcheck")]
pub mod laws {
use super::construct_uint;
Expand Down

0 comments on commit 82b2147

Please sign in to comment.