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