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