cell_automata_1d/
celloperator.rs1use crate::cellauto::CellAutomata1D;
2
3pub struct CellOperator {
4 automata: CellAutomata1D
5}
6
7impl CellOperator {
8 pub fn new(rule: u8) -> Self {
9 CellOperator {
10 automata: CellAutomata1D::with_rule(rule)
11 }
12 }
13
14 pub fn eval(&mut self, lhs: u8, rhs: u8) -> u8 {
15 fn bit_char(num: u8, pos: u8) -> char {
16 match num & (1 << (7 - pos)) {
17 0 => '0',
18 _ => '1'
19 }
20 }
21
22 let mut union_str = String::with_capacity(16);
23 for i in 0..8 {
24 union_str.push(bit_char(lhs, i));
25 union_str.push(bit_char(rhs, i));
26 }
27
28 self.automata.set_state(union_str.as_str());
29 self.automata.next();
30
31 let result = self.automata.get_state();
32 let mut result_str = String::with_capacity(8);
33
34 for i in 0..16 {
35 if i % 2 == 1 {
36 match result[i] {
37 true => result_str.push('1'),
38 false => result_str.push('0')
39 }
40 }
41 }
42
43 let result = u8::from_str_radix(result_str.as_str(), 2).unwrap();
44 result
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use crate::celloperator::*;
51
52 #[test]
53 fn cell_operator_works() {
54 let mut and_op = CellOperator::new(0xc0);
55 assert_eq!(and_op.eval(0x3c, 0x0f), 0x0c);
56 let mut not_op = CellOperator::new(0x0f);
57 assert_eq!(not_op.eval(0x3c, 0xff), 0xc3);
58 }
59}