r1cs/
wire.rs

1#[cfg(not(feature = "std"))]
2use alloc::vec::Vec;
3
4use std::cmp::Ordering;
5use std::fmt;
6use std::fmt::Formatter;
7
8/// A wire represents a witness element.
9#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
10pub struct Wire {
11    pub index: u32,
12}
13
14impl Wire {
15    /// A special wire whose value is always set to 1. This is used to create `Expression`s with
16    /// constant terms.
17    pub const ONE: Wire = Wire { index: 0 };
18}
19
20impl Ord for Wire {
21    fn cmp(&self, other: &Self) -> Ordering {
22        // For presentation, we want the 1 wire to be last. Otherwise use ascending index order.
23        if *self == Wire::ONE && *other == Wire::ONE {
24            Ordering::Equal
25        } else if *self == Wire::ONE {
26            Ordering::Greater
27        } else if *other == Wire::ONE {
28            Ordering::Less
29        } else {
30            self.index.cmp(&other.index)
31        }
32    }
33}
34
35impl PartialOrd for Wire {
36    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
37        Some(self.cmp(other))
38    }
39}
40
41impl fmt::Display for Wire {
42    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
43        if self.index == 0 {
44            write!(f, "1")
45        } else {
46            write!(f, "wire_{}", self.index)
47        }
48    }
49}
50
51/// A `Wire` whose value is constrained to be binary.
52#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
53pub struct BooleanWire {
54    pub wire: Wire,
55}
56
57/// A `Wire` which has been constrained in such a way that it can only take on a value of 0 or 1.
58impl BooleanWire {
59    /// Construct a BooleanWire from an arbitrary wire. This is only safe if you separately
60    /// constrain the wire to equal 0 or 1.
61    ///
62    /// Users should not normally call this method directly; use a method like
63    /// `GadgetBuilder::boolean_wire()` instead.
64    pub fn new_unsafe(wire: Wire) -> Self {
65        BooleanWire { wire }
66    }
67
68    pub fn wire(self) -> Wire {
69        self.wire
70    }
71}
72
73/// A "binary wire" which is comprised of several bits, each one being a boolean wire.
74#[derive(Clone, Debug)]
75pub struct BinaryWire {
76    /// The list of bits, ordered from least significant to most significant.
77    pub bits: Vec<BooleanWire>,
78}
79
80#[allow(clippy::len_without_is_empty)]
81impl BinaryWire {
82    /// The number of bits.
83    pub fn len(&self) -> usize {
84        self.bits.len()
85    }
86}