sparse_bin_mat/
binary_number.rs

1use std::fmt;
2use std::ops::{Add, AddAssign, Mul, MulAssign};
3
4type BinNumInner = u8;
5
6/// A wrapper around an integer limited to value 0 and 1.
7#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, PartialOrd, Ord)]
8pub struct BinNum {
9    pub(crate) inner: BinNumInner,
10}
11
12impl BinNum {
13    /// Returns a new BinNum.
14    ///
15    /// # Panic
16    ///
17    /// Panics if the given number is not 0 or 1.
18    pub fn new(number: BinNumInner) -> Self {
19        if !(number == 0 || number == 1) {
20            panic!("binary number must be 0 or 1")
21        }
22        BinNum { inner: number }
23    }
24
25    /// Returns the binary number 1.
26    pub fn one() -> Self {
27        BinNum { inner: 1 }
28    }
29
30    /// Returns the binary number 0.
31    pub fn zero() -> Self {
32        BinNum { inner: 0 }
33    }
34
35    /// Checks if a binary number has value 1.
36    pub fn is_one(self) -> bool {
37        self.inner == 1
38    }
39
40    /// Checks if a binary number has value 0.
41    pub fn is_zero(self) -> bool {
42        self.inner == 0
43    }
44}
45
46impl From<BinNumInner> for BinNum {
47    fn from(number: BinNumInner) -> Self {
48        Self::new(number)
49    }
50}
51
52impl From<BinNum> for BinNumInner {
53    fn from(number: BinNum) -> Self {
54        number.inner
55    }
56}
57
58impl Add<BinNum> for BinNum {
59    type Output = Self;
60    fn add(self, other: Self) -> Self {
61        BinNum {
62            inner: self.inner ^ other.inner,
63        }
64    }
65}
66
67impl AddAssign<BinNum> for BinNum {
68    fn add_assign(&mut self, other: Self) {
69        self.inner ^= other.inner;
70    }
71}
72
73impl Mul<BinNum> for BinNum {
74    type Output = Self;
75    fn mul(self, other: Self) -> Self {
76        BinNum {
77            inner: self.inner * other.inner,
78        }
79    }
80}
81
82impl MulAssign<BinNum> for BinNum {
83    fn mul_assign(&mut self, other: Self) {
84        self.inner *= other.inner;
85    }
86}
87
88impl fmt::Display for BinNum {
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        fmt::Display::fmt(&self.inner, f)
91    }
92}