-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
114 lines (99 loc) · 2.35 KB
/
mod.rs
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::core::ports::{InputPin, OutputPin};
use crate::core::AsyncComponent;
pub struct BinaryGate<T>
where
T: BinaryOp + Send,
{
input_a: InputPin,
input_b: InputPin,
output: OutputPin,
phantom_data: std::marker::PhantomData<T>,
}
impl<T> BinaryGate<T>
where
T: BinaryOp + Send,
{
pub fn new() -> Self {
Self::with_initial_values(false, false)
}
pub fn with_initial_values(input_a: bool, input_b: bool) -> Self {
Self {
input_a: InputPin::with_initial_value(input_a),
input_b: InputPin::with_initial_value(input_b),
output: OutputPin::with_initial_value(T::op(input_a, input_b)),
phantom_data: std::marker::PhantomData::default(),
}
}
pub fn input_a(&mut self) -> &mut InputPin {
&mut self.input_a
}
pub fn input_b(&mut self) -> &mut InputPin {
&mut self.input_b
}
pub fn output(&mut self) -> &mut OutputPin {
&mut self.output
}
}
impl<T> Default for BinaryGate<T>
where
T: BinaryOp + Send,
{
fn default() -> Self {
Self::new()
}
}
impl<T> AsyncComponent for BinaryGate<T>
where
T: BinaryOp + Send,
{
fn run(&mut self, stop: Arc<AtomicBool>) {
loop {
InputPin::wait_any(&mut [&mut self.input_a, &mut self.input_b]);
if stop.load(Ordering::Relaxed) {
break;
}
let output = T::op(self.input_a.value(), self.input_b.value());
println!("{}", output);
self.output.send(output);
}
}
}
pub trait BinaryOp {
fn op(a: bool, b: bool) -> bool;
}
pub struct AndOp;
impl BinaryOp for AndOp {
fn op(a: bool, b: bool) -> bool {
a && b
}
}
pub type AndGate = BinaryGate<AndOp>;
pub struct OrOp;
impl BinaryOp for OrOp {
fn op(a: bool, b: bool) -> bool {
a || b
}
}
pub type OrGate = BinaryGate<OrOp>;
pub struct EorOp;
impl BinaryOp for EorOp {
fn op(a: bool, b: bool) -> bool {
a ^ b
}
}
pub type EorGate = BinaryGate<EorOp>;
pub struct NandOp;
impl BinaryOp for NandOp {
fn op(a: bool, b: bool) -> bool {
!(a && b)
}
}
pub type NandGate = BinaryGate<NandOp>;
pub struct NorOp;
impl BinaryOp for NorOp {
fn op(a: bool, b: bool) -> bool {
!(a || b)
}
}