use std::hash::Hash;
use rustc_hash::FxHashMap;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mark {
OnPath,
Done,
}
pub enum Visit<'w, K> {
First,
OnPath(&'w [K]),
Done,
}
pub struct Walk<K> {
marks: FxHashMap<K, Mark>,
path: Vec<K>,
}
impl<K: Clone + Eq + Hash> Default for Walk<K> {
fn default() -> Self {
Self {
marks: FxHashMap::default(),
path: Vec::new(),
}
}
}
impl<K: Clone + Eq + Hash> Walk<K> {
pub fn enter(&mut self, key: K) -> Visit<'_, K> {
match self.marks.get(&key) {
Some(Mark::OnPath) => {
let start = self
.path
.iter()
.position(|walked| *walked == key)
.expect("internal error: a key on the path is in the path");
Visit::OnPath(&self.path[start..])
}
Some(Mark::Done) => Visit::Done,
None => {
self.marks.insert(key.clone(), Mark::OnPath);
self.path.push(key);
Visit::First
}
}
}
pub fn leave(&mut self) {
let key = self.pop();
self.marks.insert(key, Mark::Done);
}
pub fn backtrack(&mut self) {
let key = self.pop();
self.marks.remove(&key);
}
pub fn path(&self) -> &[K] {
&self.path
}
fn pop(&mut self) -> K {
self.path
.pop()
.expect("internal error: a walk leaves only a key it entered")
}
}
#[cfg(test)]
mod tests {
use super::{Visit, Walk};
#[test]
fn a_key_on_the_path_gives_the_cycle_from_that_key() {
let mut walk = Walk::default();
assert!(matches!(walk.enter("a"), Visit::First));
assert!(matches!(walk.enter("b"), Visit::First));
assert!(matches!(walk.enter("c"), Visit::First));
let Visit::OnPath(cycle) = walk.enter("b") else {
panic!("`b` is on the path");
};
assert_eq!(cycle, ["b", "c"]);
}
#[test]
fn a_left_key_is_done_and_a_backtracked_key_is_new() {
let mut walk = Walk::default();
assert!(matches!(walk.enter("a"), Visit::First));
assert!(matches!(walk.enter("b"), Visit::First));
walk.leave();
assert!(matches!(walk.enter("c"), Visit::First));
walk.backtrack();
assert!(matches!(walk.enter("b"), Visit::Done));
assert!(matches!(walk.enter("c"), Visit::First));
assert_eq!(walk.path(), ["a", "c"]);
}
}