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