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    /// Whether a reference to `index` names a triplet: the same as
252    /// [`Self::is_triplet`], but for a view that hides triplets, where one the
253    /// subject may refer to counts as well (issue #161).
254    fn reference_is_triplet(&mut self, index: u32) -> bool {
255        self.is_triplet(index)
256    }
257
258    /// Creates `(i: type from to)` and returns `i`.
259    ///
260    /// `type` must be a triplet; `from` and `to` must be triplets or `0`.
261    fn create_triplet(&mut self, type_id: u32, from: u32, to: u32) -> Result<u32> {
262        let markers = self.triplet_markers();
263        ensure_type(self, type_id, None)?;
264        ensure_part(self, from, None, "from")?;
265        ensure_part(self, to, None, "to")?;
266        if from == 0 && to == 0 {
267            let index = self.try_create(0, 0)?;
268            set_outer(self, index, type_id, index)?;
269            return Ok(index);
270        }
271        let pair = pair_of(self, markers, from, to)?;
272        if self.search(type_id, pair).is_none() {
273            let index = self.try_create(0, 0)?;
274            set_outer(self, index, type_id, pair)?;
275            return Ok(index);
276        }
277        let index = self.try_create(0, 0)?;
278        let duplicate = self.try_get_or_create(pair, index)?;
279        set_outer(self, index, type_id, duplicate)?;
280        Ok(index)
281    }
282
283    /// Creates a triplet `(i: i 0 0)` that is its own type: the root of a
284    /// hierarchy has to start somewhere.
285    fn create_triplet_point(&mut self) -> Result<u32> {
286        let index = self.try_create(0, 0)?;
287        self.update(index, index, index)?;
288        Ok(index)
289    }
290
291    /// Creates the point `(address: address 0 0)` at an address nothing uses,
292    /// the way a substitution query defines a triplet at an address it names.
293    fn create_triplet_point_at(&mut self, address: u32) -> Result<()> {
294        self.try_ensure_created(address)?;
295        self.update(address, address, address)?;
296        Ok(())
297    }
298
299    /// Makes the triplet at `index` `(index: type from to)`, keeping its
300    /// address, and returns the triplet as it was.
301    ///
302    /// `type` must be a triplet or `index` itself; `from` and `to` must be
303    /// triplets, `index` itself or `0`. The pair the triplet no longer uses is
304    /// collected when nothing else uses it.
305    fn update_triplet(&mut self, index: u32, type_id: u32, from: u32, to: u32) -> Result<Triplet> {
306        let markers = self.triplet_markers();
307        let Some(before) = self.get_triplet(index) else {
308            bail!("Link {index} is not a triplet.");
309        };
310        ensure_type(self, type_id, Some(index))?;
311        ensure_part(self, from, Some(index), "from")?;
312        ensure_part(self, to, Some(index), "to")?;
313        if before.type_id == type_id && before.from == from && before.to == to {
314            return Ok(before);
315        }
316        let old_target = match stored(self, index) {
317            Some(link) => link.target,
318            None => bail!("Link {index} does not exist."),
319        };
320        let new_target = if from == 0 && to == 0 {
321            index
322        } else {
323            let pair = pair_of(self, markers, from, to)?;
324            match self.search(type_id, pair) {
325                None => pair,
326                Some(taken) if taken == index => pair,
327                Some(_) => self.try_get_or_create(pair, index)?,
328            }
329        };
330        set_outer(self, index, type_id, new_target)?;
331        if old_target != new_target && old_target != index {
332            let before = stored(self, old_target)
333                .map(|link| (link, role(self, markers, link)))
334                .into_iter()
335                .collect();
336            collect(self, markers, before)?;
337        }
338        Ok(before)
339    }
340
341    /// Deletes the triplet at `index` and every triplet that uses a deleted
342    /// one as its type, from or to; returns them all, `index` first.
343    ///
344    /// Wrappers and pairs nothing uses any more are collected, so no doublet
345    /// is left behind.
346    fn delete_triplet(&mut self, index: u32) -> Result<Vec<Triplet>> {
347        let markers = self.triplet_markers();
348        let Some(first) = self.get_triplet(index) else {
349            bail!("Link {index} is not a triplet.");
350        };
351        let deleted = cascade_of(self, first);
352        // The wrappers and pairs that touch a deleted triplet, as they are now:
353        // a store that deletes what uses a deleted doublet may take some of
354        // them along, and their sources must still be collected.
355        let mut auxiliary = Vec::new();
356        for triplet in &deleted {
357            let mut touching = self.query_links(None, None, Some(triplet.index));
358            touching.extend(stored(self, triplet.index).and_then(|link| stored(self, link.target)));
359            for link in touching {
360                let doublet_role = role(self, markers, link);
361                if doublet_role.is_auxiliary() {
362                    auxiliary.push((link, doublet_role));
363                }
364            }
365        }
366        // Users go first, so a triplet is usually unused by the time it goes;
367        // what still uses it (a cycle, a doublet of somebody else) the store
368        // deletes with it, as it does with every doublet.
369        for triplet in deleted.iter().rev() {
370            if self.exists(triplet.index) {
371                self.delete(triplet.index)?;
372            }
373        }
374        collect(self, markers, auxiliary)?;
375        Ok(deleted)
376    }
377
378    /// The triplets that match `query`, in the order of their addresses.
379    ///
380    /// A restriction by index is one lookup; by from (and to) it goes through
381    /// the wrapper of the from-part and its pairs, by to through the pairs
382    /// that end at it, by type through the doublets whose source is the type.
383    /// Only a query that restricts none of them, or only an empty from or to,
384    /// reads every doublet.
385    fn each_triplet(&mut self, query: TripletQuery) -> Vec<Triplet> {
386        let markers = self.triplet_markers();
387        let mut found = match query {
388            TripletQuery {
389                index: Some(index), ..
390            } => self.get_triplet(index).into_iter().collect(),
391            TripletQuery {
392                from: Some(from),
393                to: Some(to),
394                ..
395            } if from != 0 || to != 0 => match find_pair(self, markers, from, to) {
396                Some(pair) => triplets_on_pair(self, markers, pair),
397                None => Vec::new(),
398            },
399            TripletQuery {
400                from: Some(from), ..
401            } if from != 0 => match self.search(markers.pair, from) {
402                Some(wrapper) => {
403                    let mut found = Vec::new();
404                    for pair in self.query_links(None, Some(wrapper), None) {
405                        found.extend(triplets_on_pair(self, markers, pair.index));
406                    }
407                    found
408                }
409                None => Vec::new(),
410            },
411            TripletQuery { to: Some(to), .. } if to != 0 => {
412                let mut found = Vec::new();
413                for pair in self.query_links(None, None, Some(to)) {
414                    if is_wrapper(self, markers, pair.source) {
415                        found.extend(triplets_on_pair(self, markers, pair.index));
416                    }
417                }
418                found
419            }
420            TripletQuery {
421                type_id: Some(type_id),
422                ..
423            } => {
424                let mut found = Vec::new();
425                if type_id != 0 && !markers.contains(type_id) {
426                    for link in self.query_links(None, Some(type_id), None) {
427                        if let DoubletRole::Triplet(triplet) = role(self, markers, link) {
428                            found.push(triplet);
429                        }
430                    }
431                }
432                found
433            }
434            _ => {
435                let mut found = Vec::new();
436                for link in self.all_links() {
437                    if let DoubletRole::Triplet(triplet) = role(self, markers, link) {
438                        found.push(triplet);
439                    }
440                }
441                found
442            }
443        };
444        found.retain(|triplet| query.matches(triplet));
445        found.sort_unstable();
446        found.dedup();
447        found
448    }
449
450    /// The number of triplets that match `query`.
451    fn count_triplets(&mut self, query: TripletQuery) -> usize {
452        self.each_triplet(query).len()
453    }
454
455    /// How many other doublets use the doublet `id` as their source or target.
456    fn doublet_usages(&mut self, id: u32) -> usize {
457        let as_source = self
458            .query_links(None, Some(id), None)
459            .into_iter()
460            .filter(|link| link.index != id)
461            .count();
462        let as_target = self
463            .query_links(None, None, Some(id))
464            .into_iter()
465            .filter(|link| link.index != id)
466            .count();
467        as_source + as_target
468    }
469}
470
471fn stored<L: NamedTypeLinks + ?Sized>(links: &mut L, id: u32) -> Option<Link> {
472    if id == 0 {
473        return None;
474    }
475    links.get_link(id)
476}
477
478fn is_wrapper<L: NamedTypeLinks + ?Sized>(links: &mut L, markers: TripletMarkers, id: u32) -> bool {
479    id != 0
480        && !markers.contains(id)
481        && stored(links, id).is_some_and(|link| link.source == markers.pair)
482}
483
484fn is_pair<L: NamedTypeLinks + ?Sized>(links: &mut L, markers: TripletMarkers, id: u32) -> bool {
485    if id == 0 || markers.contains(id) {
486        return false;
487    }
488    match stored(links, id) {
489        Some(link) => is_wrapper(links, markers, link.source),
490        None => false,
491    }
492}
493
494/// The from-part and to-part of the pair `pair`.
495fn parts_of_pair<L: NamedTypeLinks + ?Sized>(
496    links: &mut L,
497    markers: TripletMarkers,
498    pair: Link,
499) -> Option<(u32, u32)> {
500    let wrapper = stored(links, pair.source)?;
501    Some((markers.decode(wrapper.target), markers.decode(pair.target)))
502}
503
504/// What `link` is in the encoding; see the [module documentation](self).
505fn role<L: NamedTypeLinks + ?Sized>(
506    links: &mut L,
507    markers: TripletMarkers,
508    link: Link,
509) -> DoubletRole {
510    if markers.contains(link.index) {
511        return DoubletRole::Marker;
512    }
513    if link.source == markers.pair {
514        return DoubletRole::Wrapper;
515    }
516    if link.source == 0 || link.source == markers.nothing {
517        return DoubletRole::Foreign;
518    }
519    let Some(source) = stored(links, link.source) else {
520        return DoubletRole::Foreign;
521    };
522    if source.source == markers.pair {
523        return DoubletRole::Pair;
524    }
525    if is_wrapper(links, markers, source.source) {
526        return DoubletRole::DuplicatePair;
527    }
528    if is_pair(links, markers, source.source) {
529        // The source is a duplicate pair: nothing of ours has one.
530        return DoubletRole::Foreign;
531    }
532    if link.target == link.index {
533        return DoubletRole::Triplet(Triplet::new(link.index, link.source, 0, 0));
534    }
535    let Some(target) = stored(links, link.target) else {
536        return DoubletRole::Foreign;
537    };
538    if markers.contains(target.index) {
539        return DoubletRole::Foreign;
540    }
541    if is_wrapper(links, markers, target.source) {
542        if let Some((from, to)) = parts_of_pair(links, markers, target) {
543            return DoubletRole::Triplet(Triplet::new(link.index, link.source, from, to));
544        }
545    }
546    if target.target == link.index && is_pair(links, markers, target.source) {
547        if let Some(pair) = stored(links, target.source) {
548            if let Some((from, to)) = parts_of_pair(links, markers, pair) {
549                return DoubletRole::Triplet(Triplet::new(link.index, link.source, from, to));
550            }
551        }
552    }
553    DoubletRole::Foreign
554}
555
556fn ensure_type<T: Triplets + ?Sized>(
557    triplets: &mut T,
558    type_id: u32,
559    itself: Option<u32>,
560) -> Result<()> {
561    if type_id == 0 {
562        bail!("The type of a triplet cannot be 0.");
563    }
564    if Some(type_id) == itself || triplets.is_triplet(type_id) {
565        return Ok(());
566    }
567    bail!("The type {type_id} is not a triplet.")
568}
569
570fn ensure_part<T: Triplets + ?Sized>(
571    triplets: &mut T,
572    part: u32,
573    itself: Option<u32>,
574    name: &str,
575) -> Result<()> {
576    if part == 0 || Some(part) == itself || triplets.is_triplet(part) {
577        return Ok(());
578    }
579    bail!("The {name} part {part} is not a triplet.")
580}
581
582/// The pair of `from` and `to`, with its wrapper, created when missing.
583fn pair_of<L: NamedTypeLinks + ?Sized>(
584    links: &mut L,
585    markers: TripletMarkers,
586    from: u32,
587    to: u32,
588) -> Result<u32> {
589    let wrapper = links.try_get_or_create(markers.pair, markers.encode(from))?;
590    links.try_get_or_create(wrapper, markers.encode(to))
591}
592
593/// The pair of `from` and `to`, when there is one.
594fn find_pair<L: NamedTypeLinks + ?Sized>(
595    links: &mut L,
596    markers: TripletMarkers,
597    from: u32,
598    to: u32,
599) -> Option<u32> {
600    let wrapper = links.search(markers.pair, markers.encode(from))?;
601    links.search(wrapper, markers.encode(to))
602}
603
604/// The triplets whose parts are the pair `pair`: the outers `(T pair)` and the
605/// triplets of the duplicate pairs `(pair i)`.
606fn triplets_on_pair<L: NamedTypeLinks + ?Sized>(
607    links: &mut L,
608    markers: TripletMarkers,
609    pair: u32,
610) -> Vec<Triplet> {
611    let mut found = Vec::new();
612    for outer in links.query_links(None, None, Some(pair)) {
613        if let DoubletRole::Triplet(triplet) = role(links, markers, outer) {
614            found.push(triplet);
615        }
616    }
617    for duplicate in links.query_links(None, Some(pair), None) {
618        if let Some(outer) = stored(links, duplicate.target) {
619            if outer.target == duplicate.index {
620                if let DoubletRole::Triplet(triplet) = role(links, markers, outer) {
621                    found.push(triplet);
622                }
623            }
624        }
625    }
626    found
627}
628
629/// The triplets other than `index` whose type, from or to is `index`.
630fn users_of<T: Triplets + ?Sized>(triplets: &mut T, index: u32) -> Vec<Triplet> {
631    let mut users = triplets.each_triplet(TripletQuery::by_type(index));
632    users.extend(triplets.each_triplet(TripletQuery::by_from(index)));
633    users.extend(triplets.each_triplet(TripletQuery::by_to(index)));
634    users.retain(|user| user.index != index);
635    users.sort_unstable();
636    users.dedup();
637    users
638}
639
640/// `first` and every triplet that uses it, directly or through another one of
641/// them: what deleting `first` deletes, `first` first.
642fn cascade_of<T: Triplets + ?Sized>(triplets: &mut T, first: Triplet) -> Vec<Triplet> {
643    let mut deleted = vec![first];
644    let mut seen = HashSet::from([first.index]);
645    let mut at = 0;
646    while at < deleted.len() {
647        let used = deleted[at].index;
648        for user in users_of(triplets, used) {
649            if seen.insert(user.index) {
650                deleted.push(user);
651            }
652        }
653        at += 1;
654    }
655    deleted
656}
657
658/// Writes the outer doublet `(index: source target)`, refusing to merge it
659/// into another doublet that already is `(source target)`: the store would
660/// delete `index` instead.
661fn set_outer<L: NamedTypeLinks + ?Sized>(
662    links: &mut L,
663    index: u32,
664    source: u32,
665    target: u32,
666) -> Result<()> {
667    if let Some(link) = stored(links, index) {
668        if link.source == source && link.target == target {
669            return Ok(());
670        }
671    }
672    if let Some(existing) = links.search(source, target) {
673        if existing != index {
674            bail!("The doublet ({source} {target}) is already {existing}: triplet {index} would be merged into it.");
675        }
676    }
677    links.update(index, source, target)?;
678    Ok(())
679}
680
681/// Deletes each wrapper, pair or duplicate pair of `candidates` that nothing
682/// uses, then what it was made of, as long as nothing else uses that either.
683/// A candidate the store has already deleted leads on to what it was made of.
684fn collect<T: Triplets + ?Sized>(
685    triplets: &mut T,
686    markers: TripletMarkers,
687    candidates: Vec<(Link, DoubletRole)>,
688) -> Result<()> {
689    let leads_on = |doublet_role: DoubletRole| {
690        matches!(doublet_role, DoubletRole::Pair | DoubletRole::DuplicatePair)
691    };
692    let mut pending = Vec::new();
693    for (link, doublet_role) in candidates {
694        if triplets.exists(link.index) {
695            pending.push(link.index);
696        } else if leads_on(doublet_role) {
697            pending.push(link.source);
698        }
699    }
700    while let Some(id) = pending.pop() {
701        let Some(link) = stored(triplets, id) else {
702            continue;
703        };
704        let doublet_role = role(triplets, markers, link);
705        if !doublet_role.is_auxiliary() || triplets.doublet_usages(id) > 0 {
706            continue;
707        }
708        triplets.delete(id)?;
709        if leads_on(doublet_role) {
710            pending.push(link.source);
711        }
712    }
713    Ok(())
714}
715
716/// A decorator that stores triplets `(index: type from to)` in the doublets
717/// of the layer it wraps; see the [module documentation](self).
718pub struct TripletsOverDoublets<L: NamedTypeLinks> {
719    links: L,
720    markers: TripletMarkers,
721}
722
723impl<L: NamedTypeLinks> TripletsOverDoublets<L> {
724    /// Triplets whose wrappers start at `pair` and whose empty part is `nothing`.
725    pub fn new(links: L, pair: u32, nothing: u32) -> Self {
726        Self::with_markers(links, TripletMarkers { pair, nothing })
727    }
728
729    pub fn with_markers(links: L, markers: TripletMarkers) -> Self {
730        Self { links, markers }
731    }
732
733    /// Triplets whose markers are the points named `Pair` and `Nothing`,
734    /// created when missing.
735    pub fn with_named_markers(mut links: L) -> Result<Self> {
736        let markers = TripletMarkers::ensure(&mut links)?;
737        Ok(Self::with_markers(links, markers))
738    }
739
740    pub fn links(&self) -> &L {
741        &self.links
742    }
743
744    pub fn links_mut(&mut self) -> &mut L {
745        &mut self.links
746    }
747
748    pub fn into_inner(self) -> L {
749        self.links
750    }
751}
752
753impl<L: NamedTypeLinks> Triplets for TripletsOverDoublets<L> {
754    fn triplet_markers(&self) -> TripletMarkers {
755        self.markers
756    }
757}
758
759impl<L: NamedTypeLinks> NamedTypeLinks for TripletsOverDoublets<L> {
760    fn create(&mut self, source: u32, target: u32) -> u32 {
761        self.links.create(source, target)
762    }
763
764    fn ensure_created(&mut self, id: u32) -> u32 {
765        self.links.ensure_created(id)
766    }
767
768    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
769        self.links.try_ensure_created(id)
770    }
771
772    fn get_link(&mut self, id: u32) -> Option<Link> {
773        self.links.get_link(id)
774    }
775
776    fn exists(&mut self, id: u32) -> bool {
777        self.links.exists(id)
778    }
779
780    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
781        self.links.try_create(source, target)
782    }
783
784    fn try_get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
785        self.links.try_get_or_create(source, target)
786    }
787
788    fn reference_exists(&mut self, id: u32) -> bool {
789        self.links.reference_exists(id)
790    }
791
792    fn claims(&mut self, id: u32) -> Option<bool> {
793        self.links.claims(id)
794    }
795
796    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
797        self.links.next_created_addresses(count)
798    }
799
800    fn update_observed(
801        &mut self,
802        id: u32,
803        source: u32,
804        target: u32,
805        observer: ChangeObserver<'_>,
806    ) -> Result<Link> {
807        self.links.update_observed(id, source, target, observer)
808    }
809
810    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
811        self.links.delete_observed(id, observer)
812    }
813
814    fn all_links(&mut self) -> Vec<Link> {
815        self.links.all_links()
816    }
817
818    fn query_links(
819        &mut self,
820        index: Option<u32>,
821        source: Option<u32>,
822        target: Option<u32>,
823    ) -> Vec<Link> {
824        self.links.query_links(index, source, target)
825    }
826
827    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
828        self.links.search(source, target)
829    }
830
831    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
832        self.links.get_or_create(source, target)
833    }
834
835    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
836        self.links.get_name(id)
837    }
838
839    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
840        self.links.set_name(id, name)
841    }
842
843    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
844        self.links.get_by_name(name)
845    }
846
847    fn remove_name(&mut self, id: u32) -> Result<()> {
848        self.links.remove_name(id)
849    }
850
851    fn save(&mut self) -> Result<()> {
852        self.links.save()
853    }
854
855    fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
856        self.links.get_or_create_named(name)
857    }
858}