Skip to main content

link_cli/triplets/
mod.rs

1//! Triplets `(index: type from to)` stored in doublets, with an associative
2//! API over any [`NamedTypeLinks`] (issue #151).
3//!
4//! The encoding keeps the convention of the type hierarchy of issue #148,
5//! *the type of a link is its source*, and adds two marker points, `Pair`
6//! (`P`) and `Nothing` (`N`, which stands for the empty part `0`):
7//!
8//! | triplet            | doublets                                                        |
9//! |--------------------|-----------------------------------------------------------------|
10//! | `(i: T 0 0)`, node | `(i: T i)`                                                      |
11//! | `(i: T f t)`       | wrapper `w = (P f)`, pair `p = (w t)`, outer `(i: T p)`         |
12//! | the same, again    | the outer `(T p)` is taken, so a duplicate pair `d = (p i)` and `(i: T d)` |
13//!
14//! A zero `f` or `t` is written as `N`. Wrappers and pairs are shared by every
15//! triplet with the same parts, so they are collected as soon as nothing uses
16//! them any more. A triplet's address is the address of its outer doublet,
17//! which an update rewrites in place: the address stays and the old pair is
18//! collected. A delete removes, like a doublet delete here, every triplet that
19//! uses the deleted one as its type, from or to.
20//!
21//! Every doublet is classified by its sources alone:
22//!
23//! - `P` and `N` are the markers;
24//! - `(w: P x)` is a wrapper;
25//! - `(p: w x)` whose source is a wrapper is a pair;
26//! - `(d: p i)` whose source is a pair is a duplicate pair;
27//! - `(i: T y)` is a triplet when `y` is `i`, a pair, or a duplicate pair
28//!   `(p i)` that points back at it;
29//! - anything else, the `Extends` wiring of a [`TypesDecorator`](crate::TypesDecorator)
30//!   say, is a doublet of somebody else and is not a triplet.
31//!
32//! [`Triplets`] is the interface, with every read and write as a default
33//! method over [`NamedTypeLinks`], and [`TripletsOverDoublets`] is the
34//! decorator that implements it over any other layer. The C# counterpart is
35//! `Foundation.Data.Doublets.Cli.TripletsOverDoublets<TLinkAddress>`.
36//! `docs/TRIPLETS.md` compares this encoding with the alternatives and lists
37//! the cost of every operation.
38
39mod lino;
40mod permissions;
41mod query;
42
43use std::collections::HashSet;
44
45use anyhow::{bail, Result};
46
47use crate::link::Link;
48use crate::link_storage::ChangeObserver;
49use crate::named_type_links::NamedTypeLinks;
50use crate::types::ensure_point;
51
52pub use lino::{import_triplets_lino, triplets_to_lino};
53pub use query::{process_triplets_query, TripletChange};
54
55/// The name of the marker point of wrappers.
56pub const PAIR_MARKER_NAME: &str = "Pair";
57
58/// The name of the marker point that stands for the empty part `0`.
59pub const NOTHING_MARKER_NAME: &str = "Nothing";
60
61/// A triplet `(index: type from to)`; `from` and `to` are `0` when empty.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
63pub struct Triplet {
64    pub index: u32,
65    pub type_id: u32,
66    pub from: u32,
67    pub to: u32,
68}
69
70impl Triplet {
71    pub fn new(index: u32, type_id: u32, from: u32, to: u32) -> Self {
72        Self {
73            index,
74            type_id,
75            from,
76            to,
77        }
78    }
79}
80
81/// The two marker points of the encoding.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83pub struct TripletMarkers {
84    /// `P`, the source of every wrapper `(P f)`.
85    pub pair: u32,
86    /// `N`, which stands for the empty part `0` inside wrappers and pairs.
87    pub nothing: u32,
88}
89
90impl TripletMarkers {
91    /// The points named `Pair` and `Nothing`, each created as a point
92    /// `(x: x x)` and named when missing.
93    pub fn ensure<L: NamedTypeLinks + ?Sized>(links: &mut L) -> Result<Self> {
94        Ok(Self {
95            pair: ensure_point(links, PAIR_MARKER_NAME)?,
96            nothing: ensure_point(links, NOTHING_MARKER_NAME)?,
97        })
98    }
99
100    /// Whether `id` is one of the markers.
101    pub fn contains(&self, id: u32) -> bool {
102        id == self.pair || id == self.nothing
103    }
104
105    fn encode(&self, part: u32) -> u32 {
106        if part == 0 {
107            self.nothing
108        } else {
109            part
110        }
111    }
112
113    fn decode(&self, part: u32) -> u32 {
114        if part == self.nothing {
115            0
116        } else {
117            part
118        }
119    }
120}
121
122/// A restriction of [`Triplets::each_triplet`]: `None` matches any value,
123/// `Some(0)` an empty `from` or `to`.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
125pub struct TripletQuery {
126    pub index: Option<u32>,
127    pub type_id: Option<u32>,
128    pub from: Option<u32>,
129    pub to: Option<u32>,
130}
131
132impl TripletQuery {
133    /// Every triplet.
134    pub fn any() -> Self {
135        Self::default()
136    }
137
138    pub fn new(
139        index: Option<u32>,
140        type_id: Option<u32>,
141        from: Option<u32>,
142        to: Option<u32>,
143    ) -> Self {
144        Self {
145            index,
146            type_id,
147            from,
148            to,
149        }
150    }
151
152    pub fn by_index(index: u32) -> Self {
153        Self {
154            index: Some(index),
155            ..Self::default()
156        }
157    }
158
159    pub fn by_type(type_id: u32) -> Self {
160        Self {
161            type_id: Some(type_id),
162            ..Self::default()
163        }
164    }
165
166    pub fn by_from(from: u32) -> Self {
167        Self {
168            from: Some(from),
169            ..Self::default()
170        }
171    }
172
173    pub fn by_to(to: u32) -> Self {
174        Self {
175            to: Some(to),
176            ..Self::default()
177        }
178    }
179
180    /// Whether `triplet` satisfies every part of the restriction.
181    pub fn matches(&self, triplet: &Triplet) -> bool {
182        self.index.is_none_or(|index| index == triplet.index)
183            && self
184                .type_id
185                .is_none_or(|type_id| type_id == triplet.type_id)
186            && self.from.is_none_or(|from| from == triplet.from)
187            && self.to.is_none_or(|to| to == triplet.to)
188    }
189}
190
191/// What a doublet is in the encoding.
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub enum DoubletRole {
194    /// `Pair` or `Nothing`.
195    Marker,
196    /// `(w: P f)`, the from-part of the pairs whose source it is.
197    Wrapper,
198    /// `(p: w t)`, the from-part and to-part of a triplet.
199    Pair,
200    /// `(d: p i)`, the pair of a triplet whose outer `(T p)` another triplet took.
201    DuplicatePair,
202    /// The outer doublet of a triplet.
203    Triplet(Triplet),
204    /// A doublet the encoding does not know: not a triplet.
205    Foreign,
206}
207
208impl DoubletRole {
209    /// Whether the doublet is a wrapper, a pair or a duplicate pair.
210    pub fn is_auxiliary(&self) -> bool {
211        matches!(self, Self::Wrapper | Self::Pair | Self::DuplicatePair)
212    }
213}
214
215/// The reads and writes of triplets stored in doublets.
216///
217/// Only [`triplet_markers`](Self::triplet_markers) is required; everything
218/// else is a default method that reads and writes through `Self`, so a layer
219/// that wraps a [`TripletsOverDoublets`] can implement this trait by forwarding
220/// the markers and see every doublet the encoding writes. Any default can be
221/// overridden: [`PermissionsDecorator`](crate::PermissionsDecorator) checks a
222/// triplet as a whole, above the wrappers and pairs it is stored in.
223///
224/// The names end in `triplet` because a triplet store is still a doublet
225/// store: `create`, `update` and `delete` of [`NamedTypeLinks`] keep working
226/// on the doublets underneath.
227pub trait Triplets: NamedTypeLinks {
228    /// The markers of the encoding.
229    fn triplet_markers(&self) -> TripletMarkers;
230
231    /// What the doublet `id` is in the encoding; `None` when it is missing.
232    fn role_of(&mut self, id: u32) -> Option<DoubletRole> {
233        let markers = self.triplet_markers();
234        let link = stored(self, id)?;
235        Some(role(self, markers, link))
236    }
237
238    /// The triplet at `index`, `None` when `index` is not a triplet.
239    fn get_triplet(&mut self, index: u32) -> Option<Triplet> {
240        match self.role_of(index) {
241            Some(DoubletRole::Triplet(triplet)) => Some(triplet),
242            _ => None,
243        }
244    }
245
246    /// Whether `index` is a triplet.
247    fn is_triplet(&mut self, index: u32) -> bool {
248        self.get_triplet(index).is_some()
249    }
250
251    /// Creates `(i: type from to)` and returns `i`.
252    ///
253    /// `type` must be a triplet; `from` and `to` must be triplets or `0`.
254    fn create_triplet(&mut self, type_id: u32, from: u32, to: u32) -> Result<u32> {
255        let markers = self.triplet_markers();
256        ensure_type(self, type_id, None)?;
257        ensure_part(self, from, None, "from")?;
258        ensure_part(self, to, None, "to")?;
259        if from == 0 && to == 0 {
260            let index = self.try_create(0, 0)?;
261            set_outer(self, index, type_id, index)?;
262            return Ok(index);
263        }
264        let pair = pair_of(self, markers, from, to)?;
265        if self.search(type_id, pair).is_none() {
266            let index = self.try_create(0, 0)?;
267            set_outer(self, index, type_id, pair)?;
268            return Ok(index);
269        }
270        let index = self.try_create(0, 0)?;
271        let duplicate = self.try_get_or_create(pair, index)?;
272        set_outer(self, index, type_id, duplicate)?;
273        Ok(index)
274    }
275
276    /// Creates a triplet `(i: i 0 0)` that is its own type: the root of a
277    /// hierarchy has to start somewhere.
278    fn create_triplet_point(&mut self) -> Result<u32> {
279        let index = self.try_create(0, 0)?;
280        self.update(index, index, index)?;
281        Ok(index)
282    }
283
284    /// Creates the point `(address: address 0 0)` at an address nothing uses,
285    /// the way a substitution query defines a triplet at an address it names.
286    fn create_triplet_point_at(&mut self, address: u32) -> Result<()> {
287        self.try_ensure_created(address)?;
288        self.update(address, address, address)?;
289        Ok(())
290    }
291
292    /// Makes the triplet at `index` `(index: type from to)`, keeping its
293    /// address, and returns the triplet as it was.
294    ///
295    /// `type` must be a triplet or `index` itself; `from` and `to` must be
296    /// triplets, `index` itself or `0`. The pair the triplet no longer uses is
297    /// collected when nothing else uses it.
298    fn update_triplet(&mut self, index: u32, type_id: u32, from: u32, to: u32) -> Result<Triplet> {
299        let markers = self.triplet_markers();
300        let Some(before) = self.get_triplet(index) else {
301            bail!("Link {index} is not a triplet.");
302        };
303        ensure_type(self, type_id, Some(index))?;
304        ensure_part(self, from, Some(index), "from")?;
305        ensure_part(self, to, Some(index), "to")?;
306        if before.type_id == type_id && before.from == from && before.to == to {
307            return Ok(before);
308        }
309        let old_target = match stored(self, index) {
310            Some(link) => link.target,
311            None => bail!("Link {index} does not exist."),
312        };
313        let new_target = if from == 0 && to == 0 {
314            index
315        } else {
316            let pair = pair_of(self, markers, from, to)?;
317            match self.search(type_id, pair) {
318                None => pair,
319                Some(taken) if taken == index => pair,
320                Some(_) => self.try_get_or_create(pair, index)?,
321            }
322        };
323        set_outer(self, index, type_id, new_target)?;
324        if old_target != new_target && old_target != index {
325            let before = stored(self, old_target)
326                .map(|link| (link, role(self, markers, link)))
327                .into_iter()
328                .collect();
329            collect(self, markers, before)?;
330        }
331        Ok(before)
332    }
333
334    /// Deletes the triplet at `index` and every triplet that uses a deleted
335    /// one as its type, from or to; returns them all, `index` first.
336    ///
337    /// Wrappers and pairs nothing uses any more are collected, so no doublet
338    /// is left behind.
339    fn delete_triplet(&mut self, index: u32) -> Result<Vec<Triplet>> {
340        let markers = self.triplet_markers();
341        let Some(first) = self.get_triplet(index) else {
342            bail!("Link {index} is not a triplet.");
343        };
344        let deleted = cascade_of(self, first);
345        // The wrappers and pairs that touch a deleted triplet, as they are now:
346        // a store that deletes what uses a deleted doublet may take some of
347        // them along, and their sources must still be collected.
348        let mut auxiliary = Vec::new();
349        for triplet in &deleted {
350            let mut touching = self.query_links(None, None, Some(triplet.index));
351            touching.extend(stored(self, triplet.index).and_then(|link| stored(self, link.target)));
352            for link in touching {
353                let doublet_role = role(self, markers, link);
354                if doublet_role.is_auxiliary() {
355                    auxiliary.push((link, doublet_role));
356                }
357            }
358        }
359        // Users go first, so a triplet is usually unused by the time it goes;
360        // what still uses it (a cycle, a doublet of somebody else) the store
361        // deletes with it, as it does with every doublet.
362        for triplet in deleted.iter().rev() {
363            if self.exists(triplet.index) {
364                self.delete(triplet.index)?;
365            }
366        }
367        collect(self, markers, auxiliary)?;
368        Ok(deleted)
369    }
370
371    /// The triplets that match `query`, in the order of their addresses.
372    ///
373    /// A restriction by index is one lookup; by from (and to) it goes through
374    /// the wrapper of the from-part and its pairs, by to through the pairs
375    /// that end at it, by type through the doublets whose source is the type.
376    /// Only a query that restricts none of them, or only an empty from or to,
377    /// reads every doublet.
378    fn each_triplet(&mut self, query: TripletQuery) -> Vec<Triplet> {
379        let markers = self.triplet_markers();
380        let mut found = match query {
381            TripletQuery {
382                index: Some(index), ..
383            } => self.get_triplet(index).into_iter().collect(),
384            TripletQuery {
385                from: Some(from),
386                to: Some(to),
387                ..
388            } if from != 0 || to != 0 => match find_pair(self, markers, from, to) {
389                Some(pair) => triplets_on_pair(self, markers, pair),
390                None => Vec::new(),
391            },
392            TripletQuery {
393                from: Some(from), ..
394            } if from != 0 => match self.search(markers.pair, from) {
395                Some(wrapper) => {
396                    let mut found = Vec::new();
397                    for pair in self.query_links(None, Some(wrapper), None) {
398                        found.extend(triplets_on_pair(self, markers, pair.index));
399                    }
400                    found
401                }
402                None => Vec::new(),
403            },
404            TripletQuery { to: Some(to), .. } if to != 0 => {
405                let mut found = Vec::new();
406                for pair in self.query_links(None, None, Some(to)) {
407                    if is_wrapper(self, markers, pair.source) {
408                        found.extend(triplets_on_pair(self, markers, pair.index));
409                    }
410                }
411                found
412            }
413            TripletQuery {
414                type_id: Some(type_id),
415                ..
416            } => {
417                let mut found = Vec::new();
418                if type_id != 0 && !markers.contains(type_id) {
419                    for link in self.query_links(None, Some(type_id), None) {
420                        if let DoubletRole::Triplet(triplet) = role(self, markers, link) {
421                            found.push(triplet);
422                        }
423                    }
424                }
425                found
426            }
427            _ => {
428                let mut found = Vec::new();
429                for link in self.all_links() {
430                    if let DoubletRole::Triplet(triplet) = role(self, markers, link) {
431                        found.push(triplet);
432                    }
433                }
434                found
435            }
436        };
437        found.retain(|triplet| query.matches(triplet));
438        found.sort_unstable();
439        found.dedup();
440        found
441    }
442
443    /// The number of triplets that match `query`.
444    fn count_triplets(&mut self, query: TripletQuery) -> usize {
445        self.each_triplet(query).len()
446    }
447
448    /// How many other doublets use the doublet `id` as their source or target.
449    fn doublet_usages(&mut self, id: u32) -> usize {
450        let as_source = self
451            .query_links(None, Some(id), None)
452            .into_iter()
453            .filter(|link| link.index != id)
454            .count();
455        let as_target = self
456            .query_links(None, None, Some(id))
457            .into_iter()
458            .filter(|link| link.index != id)
459            .count();
460        as_source + as_target
461    }
462}
463
464fn stored<L: NamedTypeLinks + ?Sized>(links: &mut L, id: u32) -> Option<Link> {
465    if id == 0 {
466        return None;
467    }
468    links.get_link(id)
469}
470
471fn is_wrapper<L: NamedTypeLinks + ?Sized>(links: &mut L, markers: TripletMarkers, id: u32) -> bool {
472    id != 0
473        && !markers.contains(id)
474        && stored(links, id).is_some_and(|link| link.source == markers.pair)
475}
476
477fn is_pair<L: NamedTypeLinks + ?Sized>(links: &mut L, markers: TripletMarkers, id: u32) -> bool {
478    if id == 0 || markers.contains(id) {
479        return false;
480    }
481    match stored(links, id) {
482        Some(link) => is_wrapper(links, markers, link.source),
483        None => false,
484    }
485}
486
487/// The from-part and to-part of the pair `pair`.
488fn parts_of_pair<L: NamedTypeLinks + ?Sized>(
489    links: &mut L,
490    markers: TripletMarkers,
491    pair: Link,
492) -> Option<(u32, u32)> {
493    let wrapper = stored(links, pair.source)?;
494    Some((markers.decode(wrapper.target), markers.decode(pair.target)))
495}
496
497/// What `link` is in the encoding; see the [module documentation](self).
498fn role<L: NamedTypeLinks + ?Sized>(
499    links: &mut L,
500    markers: TripletMarkers,
501    link: Link,
502) -> DoubletRole {
503    if markers.contains(link.index) {
504        return DoubletRole::Marker;
505    }
506    if link.source == markers.pair {
507        return DoubletRole::Wrapper;
508    }
509    if link.source == 0 || link.source == markers.nothing {
510        return DoubletRole::Foreign;
511    }
512    let Some(source) = stored(links, link.source) else {
513        return DoubletRole::Foreign;
514    };
515    if source.source == markers.pair {
516        return DoubletRole::Pair;
517    }
518    if is_wrapper(links, markers, source.source) {
519        return DoubletRole::DuplicatePair;
520    }
521    if is_pair(links, markers, source.source) {
522        // The source is a duplicate pair: nothing of ours has one.
523        return DoubletRole::Foreign;
524    }
525    if link.target == link.index {
526        return DoubletRole::Triplet(Triplet::new(link.index, link.source, 0, 0));
527    }
528    let Some(target) = stored(links, link.target) else {
529        return DoubletRole::Foreign;
530    };
531    if markers.contains(target.index) {
532        return DoubletRole::Foreign;
533    }
534    if is_wrapper(links, markers, target.source) {
535        if let Some((from, to)) = parts_of_pair(links, markers, target) {
536            return DoubletRole::Triplet(Triplet::new(link.index, link.source, from, to));
537        }
538    }
539    if target.target == link.index && is_pair(links, markers, target.source) {
540        if let Some(pair) = stored(links, target.source) {
541            if let Some((from, to)) = parts_of_pair(links, markers, pair) {
542                return DoubletRole::Triplet(Triplet::new(link.index, link.source, from, to));
543            }
544        }
545    }
546    DoubletRole::Foreign
547}
548
549fn ensure_type<T: Triplets + ?Sized>(
550    triplets: &mut T,
551    type_id: u32,
552    itself: Option<u32>,
553) -> Result<()> {
554    if type_id == 0 {
555        bail!("The type of a triplet cannot be 0.");
556    }
557    if Some(type_id) == itself || triplets.is_triplet(type_id) {
558        return Ok(());
559    }
560    bail!("The type {type_id} is not a triplet.")
561}
562
563fn ensure_part<T: Triplets + ?Sized>(
564    triplets: &mut T,
565    part: u32,
566    itself: Option<u32>,
567    name: &str,
568) -> Result<()> {
569    if part == 0 || Some(part) == itself || triplets.is_triplet(part) {
570        return Ok(());
571    }
572    bail!("The {name} part {part} is not a triplet.")
573}
574
575/// The pair of `from` and `to`, with its wrapper, created when missing.
576fn pair_of<L: NamedTypeLinks + ?Sized>(
577    links: &mut L,
578    markers: TripletMarkers,
579    from: u32,
580    to: u32,
581) -> Result<u32> {
582    let wrapper = links.try_get_or_create(markers.pair, markers.encode(from))?;
583    links.try_get_or_create(wrapper, markers.encode(to))
584}
585
586/// The pair of `from` and `to`, when there is one.
587fn find_pair<L: NamedTypeLinks + ?Sized>(
588    links: &mut L,
589    markers: TripletMarkers,
590    from: u32,
591    to: u32,
592) -> Option<u32> {
593    let wrapper = links.search(markers.pair, markers.encode(from))?;
594    links.search(wrapper, markers.encode(to))
595}
596
597/// The triplets whose parts are the pair `pair`: the outers `(T pair)` and the
598/// triplets of the duplicate pairs `(pair i)`.
599fn triplets_on_pair<L: NamedTypeLinks + ?Sized>(
600    links: &mut L,
601    markers: TripletMarkers,
602    pair: u32,
603) -> Vec<Triplet> {
604    let mut found = Vec::new();
605    for outer in links.query_links(None, None, Some(pair)) {
606        if let DoubletRole::Triplet(triplet) = role(links, markers, outer) {
607            found.push(triplet);
608        }
609    }
610    for duplicate in links.query_links(None, Some(pair), None) {
611        if let Some(outer) = stored(links, duplicate.target) {
612            if outer.target == duplicate.index {
613                if let DoubletRole::Triplet(triplet) = role(links, markers, outer) {
614                    found.push(triplet);
615                }
616            }
617        }
618    }
619    found
620}
621
622/// The triplets other than `index` whose type, from or to is `index`.
623fn users_of<T: Triplets + ?Sized>(triplets: &mut T, index: u32) -> Vec<Triplet> {
624    let mut users = triplets.each_triplet(TripletQuery::by_type(index));
625    users.extend(triplets.each_triplet(TripletQuery::by_from(index)));
626    users.extend(triplets.each_triplet(TripletQuery::by_to(index)));
627    users.retain(|user| user.index != index);
628    users.sort_unstable();
629    users.dedup();
630    users
631}
632
633/// `first` and every triplet that uses it, directly or through another one of
634/// them: what deleting `first` deletes, `first` first.
635fn cascade_of<T: Triplets + ?Sized>(triplets: &mut T, first: Triplet) -> Vec<Triplet> {
636    let mut deleted = vec![first];
637    let mut seen = HashSet::from([first.index]);
638    let mut at = 0;
639    while at < deleted.len() {
640        let used = deleted[at].index;
641        for user in users_of(triplets, used) {
642            if seen.insert(user.index) {
643                deleted.push(user);
644            }
645        }
646        at += 1;
647    }
648    deleted
649}
650
651/// Writes the outer doublet `(index: source target)`, refusing to merge it
652/// into another doublet that already is `(source target)`: the store would
653/// delete `index` instead.
654fn set_outer<L: NamedTypeLinks + ?Sized>(
655    links: &mut L,
656    index: u32,
657    source: u32,
658    target: u32,
659) -> Result<()> {
660    if let Some(link) = stored(links, index) {
661        if link.source == source && link.target == target {
662            return Ok(());
663        }
664    }
665    if let Some(existing) = links.search(source, target) {
666        if existing != index {
667            bail!("The doublet ({source} {target}) is already {existing}: triplet {index} would be merged into it.");
668        }
669    }
670    links.update(index, source, target)?;
671    Ok(())
672}
673
674/// Deletes each wrapper, pair or duplicate pair of `candidates` that nothing
675/// uses, then what it was made of, as long as nothing else uses that either.
676/// A candidate the store has already deleted leads on to what it was made of.
677fn collect<T: Triplets + ?Sized>(
678    triplets: &mut T,
679    markers: TripletMarkers,
680    candidates: Vec<(Link, DoubletRole)>,
681) -> Result<()> {
682    let leads_on = |doublet_role: DoubletRole| {
683        matches!(doublet_role, DoubletRole::Pair | DoubletRole::DuplicatePair)
684    };
685    let mut pending = Vec::new();
686    for (link, doublet_role) in candidates {
687        if triplets.exists(link.index) {
688            pending.push(link.index);
689        } else if leads_on(doublet_role) {
690            pending.push(link.source);
691        }
692    }
693    while let Some(id) = pending.pop() {
694        let Some(link) = stored(triplets, id) else {
695            continue;
696        };
697        let doublet_role = role(triplets, markers, link);
698        if !doublet_role.is_auxiliary() || triplets.doublet_usages(id) > 0 {
699            continue;
700        }
701        triplets.delete(id)?;
702        if leads_on(doublet_role) {
703            pending.push(link.source);
704        }
705    }
706    Ok(())
707}
708
709/// A decorator that stores triplets `(index: type from to)` in the doublets
710/// of the layer it wraps; see the [module documentation](self).
711pub struct TripletsOverDoublets<L: NamedTypeLinks> {
712    links: L,
713    markers: TripletMarkers,
714}
715
716impl<L: NamedTypeLinks> TripletsOverDoublets<L> {
717    /// Triplets whose wrappers start at `pair` and whose empty part is `nothing`.
718    pub fn new(links: L, pair: u32, nothing: u32) -> Self {
719        Self::with_markers(links, TripletMarkers { pair, nothing })
720    }
721
722    pub fn with_markers(links: L, markers: TripletMarkers) -> Self {
723        Self { links, markers }
724    }
725
726    /// Triplets whose markers are the points named `Pair` and `Nothing`,
727    /// created when missing.
728    pub fn with_named_markers(mut links: L) -> Result<Self> {
729        let markers = TripletMarkers::ensure(&mut links)?;
730        Ok(Self::with_markers(links, markers))
731    }
732
733    pub fn links(&self) -> &L {
734        &self.links
735    }
736
737    pub fn links_mut(&mut self) -> &mut L {
738        &mut self.links
739    }
740
741    pub fn into_inner(self) -> L {
742        self.links
743    }
744}
745
746impl<L: NamedTypeLinks> Triplets for TripletsOverDoublets<L> {
747    fn triplet_markers(&self) -> TripletMarkers {
748        self.markers
749    }
750}
751
752impl<L: NamedTypeLinks> NamedTypeLinks for TripletsOverDoublets<L> {
753    fn create(&mut self, source: u32, target: u32) -> u32 {
754        self.links.create(source, target)
755    }
756
757    fn ensure_created(&mut self, id: u32) -> u32 {
758        self.links.ensure_created(id)
759    }
760
761    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
762        self.links.try_ensure_created(id)
763    }
764
765    fn get_link(&mut self, id: u32) -> Option<Link> {
766        self.links.get_link(id)
767    }
768
769    fn exists(&mut self, id: u32) -> bool {
770        self.links.exists(id)
771    }
772
773    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
774        self.links.try_create(source, target)
775    }
776
777    fn try_get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
778        self.links.try_get_or_create(source, target)
779    }
780
781    fn reference_exists(&mut self, id: u32) -> bool {
782        self.links.reference_exists(id)
783    }
784
785    fn claims(&mut self, id: u32) -> Option<bool> {
786        self.links.claims(id)
787    }
788
789    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
790        self.links.next_created_addresses(count)
791    }
792
793    fn update_observed(
794        &mut self,
795        id: u32,
796        source: u32,
797        target: u32,
798        observer: ChangeObserver<'_>,
799    ) -> Result<Link> {
800        self.links.update_observed(id, source, target, observer)
801    }
802
803    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
804        self.links.delete_observed(id, observer)
805    }
806
807    fn all_links(&mut self) -> Vec<Link> {
808        self.links.all_links()
809    }
810
811    fn query_links(
812        &mut self,
813        index: Option<u32>,
814        source: Option<u32>,
815        target: Option<u32>,
816    ) -> Vec<Link> {
817        self.links.query_links(index, source, target)
818    }
819
820    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
821        self.links.search(source, target)
822    }
823
824    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
825        self.links.get_or_create(source, target)
826    }
827
828    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
829        self.links.get_name(id)
830    }
831
832    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
833        self.links.set_name(id, name)
834    }
835
836    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
837        self.links.get_by_name(name)
838    }
839
840    fn remove_name(&mut self, id: u32) -> Result<()> {
841        self.links.remove_name(id)
842    }
843
844    fn save(&mut self) -> Result<()> {
845        self.links.save()
846    }
847
848    fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
849        self.links.get_or_create_named(name)
850    }
851}