Skip to main content

link_cli/sequences/
right_sequence_walker.rs

1use anyhow::{bail, Result};
2use std::collections::HashSet;
3
4use crate::link_storage::LinkStorage;
5use crate::sequences::{DefaultStack, TargetMatcher};
6
7#[derive(Clone, Copy, Debug)]
8pub struct RightSequenceWalker {
9    unicode_symbol_criterion_matcher: TargetMatcher,
10}
11
12impl RightSequenceWalker {
13    pub fn new(unicode_symbol_criterion_matcher: TargetMatcher) -> Self {
14        Self {
15            unicode_symbol_criterion_matcher,
16        }
17    }
18
19    /// Compatibility wrapper for valid graphs. Use [`Self::try_walk`] when
20    /// decoding persisted or caller-controlled sequence links.
21    ///
22    /// # Panics
23    /// Panics if the graph contains a missing node or a cycle.
24    pub fn walk(&self, links: &LinkStorage, sequence: u32) -> Vec<u32> {
25        self.try_walk(links, sequence)
26            .expect("Invalid sequence graph; use try_walk for fallible decoding")
27    }
28
29    /// Walk left-to-right, rejecting missing nodes and active-path cycles.
30    /// Shared subtrees are expanded for each occurrence. Traversal uses an
31    /// explicit stack and O(depth) path metadata rather than recursive calls.
32    pub fn try_walk(&self, links: &LinkStorage, sequence: u32) -> Result<Vec<u32>> {
33        let mut output = Vec::new();
34        let mut stack = DefaultStack::new();
35        let mut path = HashSet::new();
36        stack.push((sequence, false));
37
38        while let Some((element, exit)) = stack.pop() {
39            if exit {
40                path.remove(&element);
41                continue;
42            }
43            let link = links
44                .get(element)
45                .ok_or_else(|| anyhow::anyhow!("Sequence link {element} does not exist."))?;
46            if link.target == self.unicode_symbol_criterion_matcher.target() {
47                output.push(element);
48                continue;
49            }
50            if !path.insert(element) {
51                bail!("Unicode sequence cycle at link {element}.");
52            }
53            stack.push((element, true));
54            stack.push((link.target, false));
55            stack.push((link.source, false));
56        }
57
58        Ok(output)
59    }
60}