Skip to main content

dtrees_rs/caching/
helpers.rs

1use std::collections::BTreeSet;
2
3/// Position of an entry in the cache.
4pub struct CacheKey(pub usize);
5
6/// The set of items on the path from the root to the current node, kept
7/// sorted.
8#[derive(Default)]
9pub struct SearchPath {
10    inner: BTreeSet<usize>,
11}
12
13/// Result of a cache insertion.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Index {
16    /// A new (or never evaluated) entry at this position.
17    New(usize),
18    /// An entry evaluated before, at this position.
19    Existing(usize),
20}
21
22impl SearchPath {
23    pub fn new() -> Self {
24        Self {
25            inner: BTreeSet::new(),
26        }
27    }
28
29    pub fn push(&mut self, value: usize) {
30        self.inner.insert(value);
31    }
32
33    pub fn remove(&mut self, value: &usize) {
34        self.inner.remove(value);
35    }
36
37    /// The items of the path, sorted.
38    pub fn to_sorted_vec(&self) -> Vec<usize> {
39        self.inner.iter().copied().collect()
40    }
41}
42
43impl Index {
44    pub fn new_at(position: usize) -> Self {
45        Index::New(position)
46    }
47
48    pub fn existing(position: usize) -> Self {
49        Index::Existing(position)
50    }
51
52    /// Whether the entry has not been evaluated yet.
53    pub fn is_new(&self) -> bool {
54        matches!(self, Index::New(_))
55    }
56
57    pub fn position(&self) -> usize {
58        match self {
59            Index::New(pos) | Index::Existing(pos) => *pos,
60        }
61    }
62
63    /// The key of the entry.
64    pub fn to_cache_key(&self) -> CacheKey {
65        CacheKey(self.position())
66    }
67}