Skip to content

Commit

Permalink
Refactoring lookup table Display trait
Browse files Browse the repository at this point in the history
  • Loading branch information
be-next committed Dec 25, 2023
1 parent fc073b2 commit 2bc2ad9
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/core/lookup_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
// The neighborhood is represented by a tuple of three values: (left, center, right).
// The next state is represented by a single value.


#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct M1DLookupTable {
data: Vec<i8>,
Expand All @@ -26,12 +27,14 @@ macro_rules! get_index_or_err {
}

impl sdt::fmt::Display for M1DLookupTable {
fn fmt(&self, f: &mut sdt::fmt::Formatter<'_>) -> sdt::fmt::Result {
let mut result = String::new();
for (r, c, l) in self.iter_indices() {
let value = self.get(r, c, l).unwrap();
result.push_str(&format!("({}, {}, {}) -> {}\n", r, c, l, value));
}
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let result = self.iter_indices()
.map(|(r, c, l)| {
let value = self.get(r, c, l).unwrap();
format!("({}, {}, {}) -> {}\n", r, c, l, value)
})
.collect::<String>();

write!(f, "{}", result)
}
}
Expand Down Expand Up @@ -94,9 +97,7 @@ impl M1DLookupTable {
.filter(|(r, c, l)| self.get(*r, *c, *l).unwrap() == &value_to_replace)
.collect();

for (r, c, l) in indices_to_modify {
let _ = self.set(r, c, l, c).unwrap();
}
indices_to_modify.iter().for_each(|(r, c, l)| { _ = self.set(*r, *c, *l, *c).unwrap(); });

self
}
Expand Down
42 changes: 42 additions & 0 deletions tests/test_lookup_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,45 @@ fn it_finalizes() {
let result = lt.get(2, 2, 2).unwrap();
assert_eq!(*result, 1);
}

#[test]
fn it_displays_correctly() {
let num_states:i8 = 3;
let mut lt = M1DLookupTable::new(num_states, 0);

lt.iter_indices().for_each(|(r, c, l)| {
_ = lt.set(r, c, l, c);
});

let expected = "(0, 0, 0) -> 0
(0, 0, 1) -> 0
(0, 0, 2) -> 0
(0, 1, 0) -> 1
(0, 1, 1) -> 1
(0, 1, 2) -> 1
(0, 2, 0) -> 2
(0, 2, 1) -> 2
(0, 2, 2) -> 2
(1, 0, 0) -> 0
(1, 0, 1) -> 0
(1, 0, 2) -> 0
(1, 1, 0) -> 1
(1, 1, 1) -> 1
(1, 1, 2) -> 1
(1, 2, 0) -> 2
(1, 2, 1) -> 2
(1, 2, 2) -> 2
(2, 0, 0) -> 0
(2, 0, 1) -> 0
(2, 0, 2) -> 0
(2, 1, 0) -> 1
(2, 1, 1) -> 1
(2, 1, 2) -> 1
(2, 2, 0) -> 2
(2, 2, 1) -> 2
(2, 2, 2) -> 2
";

let result = format!("{}", lt);
assert_eq!(result, expected);
}

0 comments on commit 2bc2ad9

Please sign in to comment.