1use std::hash::Hash;
2
3use rustc_hash::FxHashMap;
4
5#[derive(Clone, Copy, PartialEq, Eq)]
6enum Mark {
7 OnPath,
8 Done,
9}
10
11pub enum Visit<'w, K> {
12 First,
13 OnPath(&'w [K]),
14 Done,
15}
16
17pub struct Walk<K> {
18 marks: FxHashMap<K, Mark>,
19 path: Vec<K>,
20}
21
22impl<K: Clone + Eq + Hash> Default for Walk<K> {
23 fn default() -> Self {
24 Self {
25 marks: FxHashMap::default(),
26 path: Vec::new(),
27 }
28 }
29}
30
31impl<K: Clone + Eq + Hash> Walk<K> {
32 pub fn enter(&mut self, key: K) -> Visit<'_, K> {
33 match self.marks.get(&key) {
34 Some(Mark::OnPath) => {
35 let start = self
36 .path
37 .iter()
38 .position(|walked| *walked == key)
39 .expect("internal error: a key on the path is in the path");
40 Visit::OnPath(&self.path[start..])
41 }
42 Some(Mark::Done) => Visit::Done,
43 None => {
44 self.marks.insert(key.clone(), Mark::OnPath);
45 self.path.push(key);
46 Visit::First
47 }
48 }
49 }
50
51 pub fn leave(&mut self) {
52 let key = self.pop();
53 self.marks.insert(key, Mark::Done);
54 }
55
56 pub fn backtrack(&mut self) {
57 let key = self.pop();
58 self.marks.remove(&key);
59 }
60
61 pub fn path(&self) -> &[K] {
62 &self.path
63 }
64
65 fn pop(&mut self) -> K {
66 self.path
67 .pop()
68 .expect("internal error: a walk leaves only a key it entered")
69 }
70}
71
72#[cfg(test)]
73mod tests {
74 use super::{Visit, Walk};
75
76 #[test]
77 fn a_key_on_the_path_gives_the_cycle_from_that_key() {
78 let mut walk = Walk::default();
79 assert!(matches!(walk.enter("a"), Visit::First));
80 assert!(matches!(walk.enter("b"), Visit::First));
81 assert!(matches!(walk.enter("c"), Visit::First));
82 let Visit::OnPath(cycle) = walk.enter("b") else {
83 panic!("`b` is on the path");
84 };
85 assert_eq!(cycle, ["b", "c"]);
86 }
87
88 #[test]
89 fn a_left_key_is_done_and_a_backtracked_key_is_new() {
90 let mut walk = Walk::default();
91 assert!(matches!(walk.enter("a"), Visit::First));
92 assert!(matches!(walk.enter("b"), Visit::First));
93 walk.leave();
94 assert!(matches!(walk.enter("c"), Visit::First));
95 walk.backtrack();
96 assert!(matches!(walk.enter("b"), Visit::Done));
97 assert!(matches!(walk.enter("c"), Visit::First));
98 assert_eq!(walk.path(), ["a", "c"]);
99 }
100}