1mod 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
54pub const PAIR_MARKER_NAME: &str = "Pair";
56
57pub const NOTHING_MARKER_NAME: &str = "Nothing";
59
60#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82pub struct TripletMarkers {
83 pub pair: u32,
85 pub nothing: u32,
87}
88
89impl TripletMarkers {
90 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 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#[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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub enum DoubletRole {
193 Marker,
195 Wrapper,
197 Pair,
199 DuplicatePair,
201 Triplet(Triplet),
203 Foreign,
205}
206
207impl DoubletRole {
208 pub fn is_auxiliary(&self) -> bool {
210 matches!(self, Self::Wrapper | Self::Pair | Self::DuplicatePair)
211 }
212}
213
214pub trait Triplets: NamedTypeLinks {
226 fn triplet_markers(&self) -> TripletMarkers;
228
229 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 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 fn is_triplet(&mut self, index: u32) -> bool {
246 self.get_triplet(index).is_some()
247 }
248
249 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 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 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 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 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 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 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 fn count_triplets(&mut self, query: TripletQuery) -> usize {
446 self.each_triplet(query).len()
447 }
448
449 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
488fn 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
498fn 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 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
576fn 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
587fn 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
598fn 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
623fn 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
634fn 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
657fn 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
692pub struct TripletsOverDoublets<L: NamedTypeLinks> {
695 links: L,
696 markers: TripletMarkers,
697}
698
699impl<L: NamedTypeLinks> TripletsOverDoublets<L> {
700 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 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}