Skip to main content

link_cli/
link_storage_doublets.rs

1//! Bridge between the CLI's [`LinkStorage`] and the upstream `doublets` traits.
2//!
3//! Implementing [`Links`] and [`Doublets`] for [`LinkStorage`] lets this crate
4//! reuse the `doublets::decorators` layer instead of re-implementing uniqueness
5//! resolution and cascading deletion by hand. It is the direct analogue of what
6//! the C# implementation does in
7//! `Foundation.Data.Doublets.Cli.NamedTypesDecorator.MakeLinks`:
8//!
9//! ```csharp
10//! var links = new UnitedMemoryLinks<TLinkAddress>(databaseFilename);
11//! return links.DecorateWithAutomaticUniquenessAndUsagesResolution();
12//! ```
13//!
14//! [`LinkStorage`] plays the `UnitedMemoryLinks` role — a plain store with no
15//! policy of its own — and
16//! [`DecoratorsExt::with_automatic_uniqueness_and_usages_resolution`](doublets::decorators::DecoratorsExt::with_automatic_uniqueness_and_usages_resolution)
17//! supplies the policy.
18//!
19//! The impls are also part of the public API on purpose: any embedder can now
20//! stack arbitrary upstream decorators (or its own) onto a [`LinkStorage`], and
21//! pass one anywhere a `doublets::Doublets<u32>` is expected.
22
23use std::sync::OnceLock;
24
25use doublets::data::{Flow, LinksConstants, ReadHandler, WriteHandler};
26use doublets::{Doublets, Error, Link as DoubletsLink, Links};
27
28use crate::link::Link;
29use crate::link_storage::LinkStorage;
30
31/// The [`LinksConstants`] every [`LinkStorage`] reports.
32///
33/// These are the *hybrid* constants, the direct analogue of C#'s
34/// `LinksConstants<TLinkAddress>` default for `Hybrid<uint>` addresses: `null`
35/// is `0`, internal addresses occupy the lower half of the `u32` range, and the
36/// upper half is reserved for external references.
37///
38/// The external half is not optional. A [`LinkStorage`] backing a names
39/// database stores exactly the values
40/// [`external_reference`](crate::hybrid_reference::external_reference)
41/// produces — `0 - value`, i.e. the top of the `u32` range — both for named
42/// links and for the raw character codes behind Unicode symbols. With the
43/// internal-only constants those values fall either inside `internal_range`,
44/// where
45/// [`ensure_inner_reference_exists`](doublets::decorators) would demand a
46/// stored link at that address, or exactly on a service constant: the external
47/// reference of link `4` is `0u32.wrapping_sub(4)`, which the internal-only
48/// constants define as `any`. Declaring the external range keeps every hybrid
49/// reference outside both.
50pub fn link_storage_constants() -> &'static LinksConstants<u32> {
51    static CONSTANTS: OnceLock<LinksConstants<u32>> = OnceLock::new();
52    CONSTANTS.get_or_init(LinksConstants::external)
53}
54
55fn as_doublets_link(link: &Link) -> DoubletsLink<u32> {
56    DoubletsLink::new(link.index, link.source, link.target)
57}
58
59/// Reads one part out of a raw query slice, defaulting to `null` when the slice
60/// is shorter — the same rule `doublets` uses internally.
61fn part(query: &[u32], index: usize) -> u32 {
62    query.get(index).copied().unwrap_or(0)
63}
64
65/// Every link, ordered by address.
66///
67/// Mirrors `each_core(handler, &[])` in the upstream unit store, which walks
68/// allocated addresses from `1` upwards.
69fn all(storage: &LinkStorage) -> Vec<Link> {
70    let mut matched: Vec<Link> = storage.all().into_iter().copied().collect();
71    matched.sort_by_key(|link| link.index);
72    matched
73}
74
75/// The `(any, source, target)` case, reproducing the *index* semantics of the
76/// upstream unit store rather than a plain scan.
77///
78/// In `doublets` a link is only reachable through the `(source, target)`
79/// lookups while it is attached to the source and target trees, and
80/// [`mem::united::Store::update_links`] only attaches the parts that are not
81/// `null`:
82///
83/// ```rust,ignore
84/// if place.source != T::from_byte(0) { unsafe { self.attach_source(index); } }
85/// if place.target != T::from_byte(0) { unsafe { self.attach_target(index); } }
86/// ```
87///
88/// A freshly created — or deliberately blanked — link therefore never answers a
89/// `(source, target)` query, which is exactly what keeps
90/// [`UniquenessResolver`](doublets::decorators::UniquenessResolver) from merging
91/// all the not-yet-filled links with each other. Matching that rule here is what
92/// makes the decorators behave the same on top of a [`LinkStorage`].
93fn by_pattern(storage: &LinkStorage, source: u32, target: u32) -> Vec<Link> {
94    let constants = link_storage_constants();
95    let (any, null) = (constants.any, constants.null);
96
97    // Preserve upstream null/wildcard rules while using the optional indexes.
98    if let Some(matched) = storage.indexed_query(
99        None,
100        (source != any).then_some(source),
101        (target != any).then_some(target),
102    ) {
103        if source == null || target == null {
104            return Vec::new();
105        }
106        let mut matched: Vec<Link> = matched.into_iter().copied().collect();
107        matched.sort_unstable_by_key(|link| link.index);
108        if source != any && target != any {
109            matched.truncate(1);
110        }
111        return matched;
112    }
113
114    match (source == any, target == any) {
115        (true, true) => all(storage),
116        // `targets.each_usages(target)`: the tree rooted at a null target is empty.
117        (true, false) if target == null => Vec::new(),
118        (true, false) => {
119            let mut matched: Vec<Link> = storage
120                .all()
121                .into_iter()
122                .filter(|link| link.target == target)
123                .copied()
124                .collect();
125            matched.sort_by_key(|link| link.index);
126            matched
127        }
128        // `sources.each_usages(source)`: the tree rooted at a null source is empty.
129        (false, true) if source == null => Vec::new(),
130        (false, true) => {
131            let mut matched: Vec<Link> = storage
132                .all()
133                .into_iter()
134                .filter(|link| link.source == source)
135                .copied()
136                .collect();
137            matched.sort_by_key(|link| link.index);
138            matched
139        }
140        (false, false) if source == null || target == null => Vec::new(),
141        // `sources.search(source, target)` yields at most one link; the lowest
142        // address wins so the answer never depends on hash map ordering.
143        (false, false) => storage
144            .all()
145            .into_iter()
146            .filter(|link| link.source == source && link.target == target)
147            .min_by_key(|link| link.index)
148            .copied()
149            .into_iter()
150            .collect(),
151    }
152}
153
154/// Links matching `query`, ordered by address so that every traversal (and
155/// therefore every cascade) is deterministic regardless of hash map ordering.
156///
157/// This is a faithful port of `each_core` in the upstream unit store, including
158/// its handling of one- and two-element queries and of the `any` constant.
159/// Query shapes the raw interface does not define match nothing.
160fn matching(storage: &LinkStorage, query: &[u32]) -> Vec<Link> {
161    let any = link_storage_constants().any;
162
163    match *query {
164        [] => all(storage),
165        [index] if index == any => all(storage),
166        [index] => storage.get(index).copied().into_iter().collect(),
167        [index, value] if index == any && value == any => all(storage),
168        [index, value] if index == any => {
169            // Upstream unions the two usage trees without deduplicating, so a
170            // link that both starts and ends at `value` is visited twice.
171            let mut matched = by_pattern(storage, value, any);
172            matched.extend(by_pattern(storage, any, value));
173            matched
174        }
175        [index, value] => storage
176            .get(index)
177            .filter(|link| value == any || link.source == value || link.target == value)
178            .copied()
179            .into_iter()
180            .collect(),
181        [index, source, target] if index == any => by_pattern(storage, source, target),
182        [index, source, target] => storage
183            .get(index)
184            .filter(|link| {
185                (source == any || link.source == source) && (target == any || link.target == target)
186            })
187            .copied()
188            .into_iter()
189            .collect(),
190        _ => Vec::new(),
191    }
192}
193
194impl Links<u32> for LinkStorage {
195    fn constants(&self) -> &LinksConstants<u32> {
196        link_storage_constants()
197    }
198
199    fn count_links(&self, query: &[u32]) -> u32 {
200        matching(self, query).len() as u32
201    }
202
203    fn create_links(
204        &mut self,
205        _query: &[u32],
206        handler: WriteHandler<'_, u32>,
207    ) -> Result<Flow, Error<u32>> {
208        let index = self.create(0, 0);
209        let created = Link::new(index, 0, 0);
210        Ok(handler(DoubletsLink::nothing(), as_doublets_link(&created)))
211    }
212
213    fn each_links(&self, query: &[u32], handler: ReadHandler<'_, u32>) -> Flow {
214        for link in matching(self, query) {
215            if handler(as_doublets_link(&link)) == Flow::Break {
216                return Flow::Break;
217            }
218        }
219        Flow::Continue
220    }
221
222    fn update_links(
223        &mut self,
224        query: &[u32],
225        change: &[u32],
226        handler: WriteHandler<'_, u32>,
227    ) -> Result<Flow, Error<u32>> {
228        let index = part(query, 0);
229        let source = part(change, 1);
230        let target = part(change, 2);
231        let before = self
232            .update_raw(index, source, target)
233            .map_err(|_| Error::NotExists(index))?;
234        let after = Link::new(index, source, target);
235        Ok(handler(as_doublets_link(&before), as_doublets_link(&after)))
236    }
237
238    fn delete_links(
239        &mut self,
240        query: &[u32],
241        handler: WriteHandler<'_, u32>,
242    ) -> Result<Flow, Error<u32>> {
243        let index = part(query, 0);
244        let before = self
245            .delete_raw(index)
246            .map_err(|_| Error::NotExists(index))?;
247        Ok(handler(as_doublets_link(&before), DoubletsLink::nothing()))
248    }
249}
250
251impl Doublets<u32> for LinkStorage {
252    fn get_link(&self, index: u32) -> Option<DoubletsLink<u32>> {
253        self.get(index).map(as_doublets_link)
254    }
255}
256
257/// `doublets` ships no blanket implementation for references, so decorating a
258/// borrowed store (instead of moving it into the decorator) needs this
259/// forwarding impl. It is what lets [`LinkStorage`] decorate itself for the
260/// duration of a single operation.
261impl Links<u32> for &mut LinkStorage {
262    fn constants(&self) -> &LinksConstants<u32> {
263        (**self).constants()
264    }
265
266    fn count_links(&self, query: &[u32]) -> u32 {
267        (**self).count_links(query)
268    }
269
270    fn create_links(
271        &mut self,
272        query: &[u32],
273        handler: WriteHandler<'_, u32>,
274    ) -> Result<Flow, Error<u32>> {
275        (**self).create_links(query, handler)
276    }
277
278    fn each_links(&self, query: &[u32], handler: ReadHandler<'_, u32>) -> Flow {
279        (**self).each_links(query, handler)
280    }
281
282    fn update_links(
283        &mut self,
284        query: &[u32],
285        change: &[u32],
286        handler: WriteHandler<'_, u32>,
287    ) -> Result<Flow, Error<u32>> {
288        (**self).update_links(query, change, handler)
289    }
290
291    fn delete_links(
292        &mut self,
293        query: &[u32],
294        handler: WriteHandler<'_, u32>,
295    ) -> Result<Flow, Error<u32>> {
296        (**self).delete_links(query, handler)
297    }
298}
299
300impl Doublets<u32> for &mut LinkStorage {
301    fn get_link(&self, index: u32) -> Option<DoubletsLink<u32>> {
302        (**self).get_link(index)
303    }
304}