-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrule.rs
225 lines (202 loc) · 6.36 KB
/
rule.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
use crate::part::{Part, Unit};
use std::{fmt::{Debug, Display}, num::ParseIntError, ops::Range, rc::Rc, str::FromStr};
#[derive(Clone, Copy)]
pub(crate) enum PartVar { X = 0, M, A, S }
impl Debug for PartVar {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PartVar::X => write!(f, "x"),
PartVar::M => write!(f, "m"),
PartVar::A => write!(f, "a"),
PartVar::S => write!(f, "s"),
}
}
}
enum Operand { GT, LT }
impl Debug for Operand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Operand::GT => write!(f, ">"),
Operand::LT => write!(f, "<"),
}
}
}
pub(crate) struct Condition {
var: PartVar,
operand: Operand,
value: Unit,
}
impl Condition {
pub(crate) fn part(&self) -> PartVar {
self.var
}
fn validate(&self, part: Part) -> bool {
match (&self.var, &self.operand) {
(PartVar::X, Operand::GT) => part.x > self.value,
(PartVar::X, Operand::LT) => part.x < self.value,
(PartVar::M, Operand::GT) => part.m > self.value,
(PartVar::M, Operand::LT) => part.m < self.value,
(PartVar::S, Operand::GT) => part.s > self.value,
(PartVar::S, Operand::LT) => part.s < self.value,
(PartVar::A, Operand::GT) => part.a > self.value,
(PartVar::A, Operand::LT) => part.a < self.value,
}
}
pub(crate) fn partition(&self, rng: &Range<Unit>) -> (Range<Unit>,Range<Unit>) {
if rng.contains(&self.value) {
match self.operand {
Operand::GT => (self.value+1..rng.end, rng.start..self.value+1),
Operand::LT => (rng.start..self.value, self.value..rng.end ),
}
} else {
panic!("Condition::partition - value out of input range")
}
}
}
impl FromStr for Condition {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Condition {
var: match &s[..1] {
"x" => PartVar::X,
"m" => PartVar::M,
"a" => PartVar::A,
"s" => PartVar::S,
_ => panic!("Condition::operand::from_str(): invalid part variable"),
},
operand: match &s[1..2] {
">" => Operand::GT,
"<" => Operand::LT,
_ => panic!("Condition::operand::from_str(): invalid operand"),
},
value: Unit::from_str(&s[2..]).expect("Condition::value::from_str(): invalid number"),
})
}
}
impl Debug for Condition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}{:?}{:?}", self.var, self.operand, self.value)
}
}
impl Display for Condition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<Self as Debug>::fmt(self, f)
}
}
#[derive(Clone, PartialEq, Eq)]
pub(crate) enum Action {
WorkFlow(Rc<str>),
Accept,
Reject,
}
impl FromStr for Action {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"A" => Self::Accept,
"R" => Self::Reject,
wf => Self::WorkFlow(wf.into()),
})
}
}
impl Debug for Action {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Action::WorkFlow(s) => write!(f, "{}", s),
Action::Accept => write!(f, "A"),
Action::Reject => write!(f, "R"),
}
}
}
pub(crate) enum Rule {
// each rule specifies a condition and where to send the part if the condition is true
// The last rule in each workflow has no condition and always applies if reached.
ConAct(Condition, Action),
Act(Action),
}
impl Rule {
pub(crate) fn validate(&self, part: Part) -> Option<Action> {
match self {
Rule::ConAct(c, a) if c.validate(part) => Some(a.clone()),
Rule::Act(a) => Some(a.clone()),
_ => None
}
}
}
impl FromStr for Rule {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
// x>10:one, m<20:two, a>30:R, A
let mut s = s.split(':');
let o = match (s.next(), s.next()) {
(Some(s), None) => Self::Act(
s.parse::<Action>()
.expect("Rule::Act::Action::from_str failed"),
),
(Some(op), Some(res)) => Self::ConAct(
op.parse::<Condition>()
.expect("Rule::ConAct::Condition::from_str failed"),
res.parse::<Action>()
.expect("Rule::ConAct::Action::from_str failed"),
),
_ => return Err(()),
};
Ok(o)
}
}
impl Debug for Rule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Rule::ConAct(c, r) => write!(f, "{:?}:{:?}", c, r),
Rule::Act(r) => write!(f, "{:?}", r),
}
}
}
impl Display for Rule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<Self as Debug>::fmt(self, f)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::workflow::Workflow;
#[test]
fn test_rule_validate() {
let mut res = [
Some(Action::WorkFlow("one".into())),
None,
Some(Action::WorkFlow("two".into())),
None,
Some(Action::Reject),
None,
Some(Action::Accept),
]
.into_iter();
let wf = "ex{x>10:one,x<10:one,m<20:two,m>20:two,a<30:R,a>30:R,A}"
.parse::<Workflow>()
.expect("Ops");
let part = Part {
x: 11,
m: 0,
a: 20,
s: 0,
};
wf.iter().for_each(|rule| {
println!("{:?} => {:?} = {:?}", rule, part, rule.validate(part));
assert_eq!(
format!("{:?}", res.next().unwrap()),
format!("{:?}", rule.validate(part))
);
});
}
#[test]
fn test_rule_parse() {
let inp = "x>10:one\nm<20:two\na>30:R\nA";
inp.lines().for_each(|s| {
let r = s.parse::<Rule>().expect("Rule::parse() error!");
println!("{:?}", r);
assert_eq!(&format!("{:?}", r), &s)
})
}
}