Skip to content

Commit

Permalink
Add operators &, |, ! for Tracer<Bit> (#88)
Browse files Browse the repository at this point in the history
* Implement BitAnd, Not, BitOr traits for Tracer<Bit>

* Cleanup

* Run fmt
  • Loading branch information
voltrevo authored Nov 27, 2023
1 parent cddd59a commit 33ac765
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 8 deletions.
42 changes: 35 additions & 7 deletions mpz-circuits/src/ops/binary.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::ops::BitXor;
use std::ops::{BitAnd, BitOr, BitXor, Not};

use crate::{
components::{Feed, Node},
Expand Down Expand Up @@ -212,19 +212,47 @@ pub(crate) fn inv_nbit<const N: usize>(
std::array::from_fn(|n| state.add_inv_gate(a[n]))
}

impl<'a> BitXor<Tracer<'a, Bit>> for Tracer<'a, Bit> {
impl<'a> BitXor for Tracer<'a, Bit> {
type Output = Tracer<'a, Bit>;

fn bitxor(self, rhs: Tracer<'a, Bit>) -> Self::Output {
let mut state = self.state.borrow_mut();
let out = self
.state
.borrow_mut()
.add_xor_gate(self.node(), rhs.node());

let out = state.add_xor_gate(self.to_inner().nodes()[0], rhs.to_inner().nodes()[0]);
Tracer::new(self.state, Bit::new([out]))
}
}

impl<'a> BitAnd for Tracer<'a, Bit> {
type Output = Tracer<'a, Bit>;

fn bitand(self, rhs: Self) -> Self::Output {
let out = self
.state
.borrow_mut()
.add_and_gate(self.node(), rhs.node());

Tracer::new(self.state, Bit::new([out]))
}
}

impl<'a> Not for Tracer<'a, Bit> {
type Output = Tracer<'a, Bit>;

let value = Bit::new([out]);
fn not(self) -> Self::Output {
let out = self.state.borrow_mut().add_inv_gate(self.node());

drop(state);
Tracer::new(self.state, Bit::new([out]))
}
}

impl<'a> BitOr for Tracer<'a, Bit> {
type Output = Tracer<'a, Bit>;

Tracer::new(self.state, value)
fn bitor(self, rhs: Self) -> Self::Output {
!(!self & !rhs)
}
}

Expand Down
13 changes: 12 additions & 1 deletion mpz-circuits/src/tracer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::cell::RefCell;

use crate::{builder::BuilderState, types::BinaryRepr};
use crate::{
builder::BuilderState,
types::{BinaryRepr, Bit},
Feed, Node,
};

/// A wrapper type for tracing operations applied to a value.
///
Expand Down Expand Up @@ -50,3 +54,10 @@ where
BinaryRepr::Array(tracer.into_iter().map(|tracer| tracer.into()).collect())
}
}

impl<'a> Tracer<'a, Bit> {
/// Returns the single node associated with the bit.
pub fn node(&self) -> Node<Feed> {
self.to_inner().nodes()[0]
}
}

0 comments on commit 33ac765

Please sign in to comment.