Skip to main content

link_cli/
indexed_links.rs

1//! Optional secondary-index decorator for the in-memory links map.
2//!
3//! Enabled by [`LinkStorage::with_indexed_lookups`](crate::LinkStorage::with_indexed_lookups).
4//! The undecorated map remains available for algorithm comparisons. Indexes
5//! are maintained at the raw insertion/removal boundary, including writes made
6//! by upstream uniqueness and usages-resolution decorators.
7
8use std::collections::{BTreeSet, HashMap};
9use std::ops::Deref;
10
11use crate::Link;
12
13type Addresses<K> = HashMap<K, BTreeSet<u32>>;
14
15/// Adds exact-pair, source and target indexes to a links map.
16///
17/// Use the `with_indexed_lookups` builders on [`crate::LinkStorage`] or
18/// [`crate::NamedTypesDecorator`] to compose this decorator. Duplicate pairs
19/// retain every address; searches select the lowest address, just as scans do.
20#[derive(Default)]
21pub struct IndexedLinksDecorator {
22    inner: HashMap<u32, Link>,
23    pairs: Addresses<(u32, u32)>,
24    sources: Addresses<u32>,
25    targets: Addresses<u32>,
26}
27
28impl IndexedLinksDecorator {
29    fn insert(&mut self, link: Link) -> Option<Link> {
30        let previous = self.remove(link.index);
31        self.pairs
32            .entry((link.source, link.target))
33            .or_default()
34            .insert(link.index);
35        self.sources
36            .entry(link.source)
37            .or_default()
38            .insert(link.index);
39        self.targets
40            .entry(link.target)
41            .or_default()
42            .insert(link.index);
43        self.inner.insert(link.index, link);
44        previous
45    }
46
47    fn remove(&mut self, id: u32) -> Option<Link> {
48        let link = self.inner.remove(&id)?;
49        remove_address(&mut self.pairs, (link.source, link.target), id);
50        remove_address(&mut self.sources, link.source, id);
51        remove_address(&mut self.targets, link.target, id);
52        Some(link)
53    }
54
55    pub(crate) fn search(&self, source: u32, target: u32) -> Option<u32> {
56        self.pairs.get(&(source, target))?.first().copied()
57    }
58
59    pub(crate) fn query(
60        &self,
61        index: Option<u32>,
62        source: Option<u32>,
63        target: Option<u32>,
64    ) -> Vec<&Link> {
65        if let Some(id) = index {
66            return self
67                .inner
68                .get(&id)
69                .filter(|link| {
70                    source.is_none_or(|value| link.source == value)
71                        && target.is_none_or(|value| link.target == value)
72                })
73                .into_iter()
74                .collect();
75        }
76        let addresses = match (source, target) {
77            (Some(source), Some(target)) => self.pairs.get(&(source, target)),
78            (Some(source), None) => self.sources.get(&source),
79            (None, Some(target)) => self.targets.get(&target),
80            (None, None) => return self.inner.values().collect(),
81        };
82        addresses
83            .into_iter()
84            .flatten()
85            .filter_map(|id| self.inner.get(id))
86            .collect()
87    }
88}
89
90fn remove_address<K: std::hash::Hash + Eq>(index: &mut Addresses<K>, key: K, address: u32) {
91    if let Some(addresses) = index.get_mut(&key) {
92        addresses.remove(&address);
93        if addresses.is_empty() {
94            index.remove(&key);
95        }
96    }
97}
98
99/// Read access is shared, but every write goes through `insert`, `remove` or
100/// `clear`: callers cannot obtain a mutable map reference and stale the indexes.
101pub(crate) enum LinksMap {
102    Plain(HashMap<u32, Link>),
103    Indexed(IndexedLinksDecorator),
104}
105
106impl Default for LinksMap {
107    fn default() -> Self {
108        Self::Plain(HashMap::new())
109    }
110}
111
112impl Deref for LinksMap {
113    type Target = HashMap<u32, Link>;
114    fn deref(&self) -> &Self::Target {
115        match self {
116            Self::Plain(map) => map,
117            Self::Indexed(index) => &index.inner,
118        }
119    }
120}
121
122impl LinksMap {
123    pub(crate) fn enable_index(&mut self) {
124        if matches!(self, Self::Plain(_)) {
125            let links = std::mem::take(self);
126            let mut indexed = IndexedLinksDecorator::default();
127            for link in links.values() {
128                indexed.insert(*link);
129            }
130            *self = Self::Indexed(indexed);
131        }
132    }
133
134    pub(crate) fn indexed(&self) -> Option<&IndexedLinksDecorator> {
135        match self {
136            Self::Indexed(index) => Some(index),
137            _ => None,
138        }
139    }
140
141    pub(crate) fn insert(&mut self, id: u32, link: Link) -> Option<Link> {
142        debug_assert_eq!(id, link.index);
143        match self {
144            Self::Plain(map) => map.insert(id, link),
145            Self::Indexed(index) => index.insert(link),
146        }
147    }
148
149    pub(crate) fn remove(&mut self, id: &u32) -> Option<Link> {
150        match self {
151            Self::Plain(map) => map.remove(id),
152            Self::Indexed(index) => index.remove(*id),
153        }
154    }
155}