Skip to content

Commit

Permalink
feat: implement bitwise and & or operations for FieldElement (xJona…
Browse files Browse the repository at this point in the history
  • Loading branch information
xJonathanLEI authored Jun 23, 2022
1 parent 23f3b07 commit 4ee3b7f
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions starknet-ff/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,34 @@ impl std::ops::Rem<FieldElement> for FieldElement {
}
}

impl std::ops::BitAnd<FieldElement> for FieldElement {
type Output = FieldElement;

fn bitand(self, rhs: FieldElement) -> Self::Output {
let lhs: U256 = (&self).into();
let rhs: U256 = (&rhs).into();

// It's safe to unwrap here since the result is never out of range
FieldElement {
inner: Fp256::<FrParameters>::from_repr(u256_to_biginteger256(&(lhs & rhs))).unwrap(),
}
}
}

impl std::ops::BitOr<FieldElement> for FieldElement {
type Output = FieldElement;

fn bitor(self, rhs: FieldElement) -> Self::Output {
let lhs: U256 = (&self).into();
let rhs: U256 = (&rhs).into();

// It's safe to unwrap here since the result is never out of range
FieldElement {
inner: Fp256::<FrParameters>::from_repr(u256_to_biginteger256(&(lhs | rhs))).unwrap(),
}
}
}

impl Debug for FieldElement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FieldElement")
Expand Down Expand Up @@ -690,6 +718,30 @@ mod tests {
}
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn test_bitwise_and() {
let operands = [[123456_u64, 567890], [613221132151, 4523451]];

for item in operands.iter() {
let lhs: FieldElement = item[0].into();
let rhs: FieldElement = item[1].into();
assert_eq!(lhs & rhs, (item[0] & item[1]).into());
}
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn test_bitwise_or() {
let operands = [[123456_u64, 567890], [613221132151, 4523451]];

for item in operands.iter() {
let lhs: FieldElement = item[0].into();
let rhs: FieldElement = item[1].into();
assert_eq!(lhs | rhs, (item[0] | item[1]).into());
}
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn test_floor_division() {
Expand Down

0 comments on commit 4ee3b7f

Please sign in to comment.