link_cli/link_storage.rs
1//! LinkStorage - Persistent storage for links
2//!
3//! This module provides the LinkStorage struct for managing link persistence.
4
5use anyhow::{Context, Result};
6use doublets::decorators::DecoratorsExt;
7use doublets::Doublets;
8use std::collections::{HashMap, HashSet};
9use std::fs::{File, OpenOptions};
10use std::io::{BufRead, BufReader, BufWriter, Write};
11use std::path::{Path, PathBuf};
12
13use crate::error::LinkError;
14use crate::indexed_links::LinksMap;
15use crate::link::Link;
16use crate::named_type_links::escape_lino_reference;
17use crate::storage::StorageRevision;
18use crate::text_storage_format::{
19 name_metadata, needs_name_metadata, parse_link_line, parse_name_metadata, NAME_HEADER,
20};
21
22/// Callback invoked once per `(before, after)` change a write produced.
23///
24/// The upstream decorators turn a single write into a cascade of changes, so
25/// the layers above the storage — names, transactions, the query processor —
26/// only stay in sync if they can see all of them. This is the equivalent of the
27/// `WriteHandler` the C# implementation threads through every decorator. A
28/// change whose `after` [`is null`](Link::is_null) is a deletion.
29pub type ChangeObserver<'a, T = u32> =
30 &'a mut dyn FnMut(crate::GenericLink<T>, crate::GenericLink<T>);
31
32/// Adapts a [`ChangeObserver`] to the `doublets` write handler signature.
33fn observe(
34 observer: &mut dyn FnMut(Link, Link),
35 before: doublets::Link<u32>,
36 after: doublets::Link<u32>,
37) -> doublets::data::Flow {
38 observer(Link::from(before), Link::from(after));
39 doublets::data::Flow::Continue
40}
41
42/// The file a save writes before it replaces `db_path`: `db.links` is saved
43/// as `db.links.saving` in the same directory, so the rename never crosses
44/// file systems.
45fn saving_path(db_path: &Path) -> PathBuf {
46 let mut name = db_path.file_name().unwrap_or_default().to_os_string();
47 name.push(".saving");
48 db_path.with_file_name(name)
49}
50
51/// Prefix of the database line that records the freed addresses.
52///
53/// It is a comment so that a database written by this version still loads in
54/// one that predates it, and so that a database written before it still loads
55/// here — [`LinkStorage::restore_unused`] reconstructs the list when the line
56/// is absent.
57const UNUSED_HEADER: &str = "# unused:";
58
59/// LinkStorage provides persistent storage for links
60/// Corresponds to the storage functionality in NamedLinksDecorator in C#
61pub struct LinkStorage {
62 links: LinksMap,
63 names: HashMap<u32, String>,
64 name_to_id: HashMap<String, u32>,
65 /// The highest address ever handed out and not given back, i.e. the
66 /// `AllocatedLinks` counter of the C# store.
67 allocated: u32,
68 /// Addresses below [`Self::allocated`] that were freed and can be handed
69 /// out again, most recently freed last.
70 ///
71 /// The C# store keeps the same set as a linked list threaded through the
72 /// freed links themselves, pushing and popping at its head; a stack is the
73 /// same structure without the threading.
74 unused: Vec<u32>,
75 db_path: PathBuf,
76 revision: StorageRevision,
77 trace: bool,
78}
79
80impl LinkStorage {
81 /// Creates a new LinkStorage instance
82 ///
83 /// The database location is accepted as any [`AsRef<Path>`], so
84 /// embedding applications can pass a `PathBuf` (or an `OsStr` on
85 /// platforms with non-UTF-8 paths) instead of a `&str`.
86 pub fn new<P: AsRef<Path>>(db_path: P, trace: bool) -> Result<Self> {
87 let db_path = db_path.as_ref().to_path_buf();
88 let exists = db_path.exists();
89 let mut storage = Self {
90 links: LinksMap::default(),
91 names: HashMap::new(),
92 name_to_id: HashMap::new(),
93 allocated: 0,
94 unused: Vec::new(),
95 db_path,
96 revision: StorageRevision::default(),
97 trace,
98 };
99
100 // Load existing database if it exists
101 if exists {
102 storage.load()?;
103 }
104 storage.revision = StorageRevision::of(&storage.db_path)?;
105
106 Ok(storage)
107 }
108
109 /// Creates a storage that lives only in memory: it never reads or writes
110 /// a file, and [`LinkStorage::save`] keeps nothing.
111 ///
112 /// This is the store of the browser workbench, where there is no file
113 /// system, so queries there merge, cascade and reuse addresses exactly as
114 /// they do in the CLI.
115 pub fn in_memory(trace: bool) -> Self {
116 Self {
117 links: LinksMap::default(),
118 names: HashMap::new(),
119 name_to_id: HashMap::new(),
120 allocated: 0,
121 unused: Vec::new(),
122 db_path: PathBuf::new(),
123 revision: StorageRevision::default(),
124 trace,
125 }
126 }
127
128 /// Own the exact recycling state for query preview without file I/O.
129 pub(crate) fn query_copy(&self) -> Self {
130 let mut copy = Self::in_memory(false);
131 copy.links = LinksMap::Plain(self.links.iter().map(|(id, row)| (*id, *row)).collect());
132 copy.names = self.names.clone();
133 copy.name_to_id = self.name_to_id.clone();
134 copy.allocated = self.allocated;
135 copy.unused = self.unused.clone();
136 if self.links.indexed().is_some() {
137 copy.enable_indexed_lookups();
138 }
139 copy
140 }
141
142 /// Adds an optional lookup-index decorator, retaining the scan-based
143 /// implementation when this builder is not called. Indexes use O(n) memory
144 /// and are rebuilt from persisted links when enabled after opening a store.
145 pub fn with_indexed_lookups(mut self) -> Self {
146 self.enable_indexed_lookups();
147 self
148 }
149
150 pub(crate) fn enable_indexed_lookups(&mut self) {
151 self.links.enable_index();
152 if self.trace {
153 crate::diagnostics::stderr!(
154 "[TRACE] IndexedLinksDecorator enabled for {} links",
155 self.links.len()
156 );
157 }
158 }
159
160 pub(crate) fn indexed_query(
161 &self,
162 index: Option<u32>,
163 source: Option<u32>,
164 target: Option<u32>,
165 ) -> Option<Vec<&Link>> {
166 self.links
167 .indexed()
168 .map(|lookup| lookup.query(index, source, target))
169 }
170
171 /// Whether this storage was made by [`LinkStorage::in_memory`].
172 pub fn is_in_memory(&self) -> bool {
173 self.db_path.as_os_str().is_empty()
174 }
175
176 /// The database file this storage reads from and writes to, empty for an
177 /// [in-memory](LinkStorage::in_memory) storage.
178 pub fn database_path(&self) -> &Path {
179 &self.db_path
180 }
181
182 /// The revision of the database file observed at the last load or save.
183 pub fn observed_revision(&self) -> StorageRevision {
184 self.revision
185 }
186
187 /// Re-reads the database file's revision fingerprint, marking the
188 /// current on-disk state as "seen" for
189 /// [`LinksStorage::has_external_changes`](crate::LinksStorage::has_external_changes).
190 pub fn refresh_observed_revision(&mut self) -> Result<(), LinkError> {
191 if self.is_in_memory() {
192 return Ok(());
193 }
194 self.revision = StorageRevision::of(&self.db_path)?;
195 Ok(())
196 }
197
198 /// Replaces in-memory state only after the entire database loads successfully.
199 pub fn reload_from_disk(&mut self) -> Result<()> {
200 let mut loaded = if self.is_in_memory() {
201 Self::in_memory(self.trace)
202 } else {
203 Self::new(&self.db_path, self.trace)?
204 };
205 if self.links.indexed().is_some() {
206 loaded.enable_indexed_lookups();
207 }
208 *self = loaded;
209 Ok(())
210 }
211
212 /// Loads links from the database file
213 fn load(&mut self) -> Result<()> {
214 let file = File::open(&self.db_path)
215 .with_context(|| format!("Failed to open database: {}", self.db_path.display()))?;
216
217 let reader = BufReader::new(file);
218 let mut recorded_unused = None;
219
220 for (number, line) in reader.lines().enumerate() {
221 let line = line.with_context(|| {
222 format!(
223 "Failed to read {} at line {}",
224 self.db_path.display(),
225 number + 1
226 )
227 })?;
228 let line = line.trim();
229
230 if let Some(addresses) = line.strip_prefix(UNUSED_HEADER) {
231 recorded_unused = Some(Self::parse_unused_header(addresses));
232 continue;
233 }
234
235 if let Some(metadata) = line.strip_prefix(NAME_HEADER) {
236 let (id, name) = parse_name_metadata(metadata).with_context(|| {
237 format!(
238 "Invalid name metadata in {} at line {}",
239 self.db_path.display(),
240 number + 1
241 )
242 })?;
243 self.set_name(id, &name);
244 continue;
245 }
246
247 if line.is_empty() || line.starts_with('#') {
248 continue;
249 }
250
251 // Parse link format: (index source target) or (index source target "name")
252 if let Some((link, name)) = parse_link_line(line) {
253 self.links.insert(link.index, link);
254 if link.index > self.allocated {
255 self.allocated = link.index;
256 }
257 if let Some(name) = name {
258 self.set_name(link.index, &name);
259 }
260 }
261 }
262
263 self.unused = self.restore_unused(recorded_unused);
264
265 if self.trace {
266 crate::diagnostics::stderr!(
267 "[TRACE] Loaded {} links from {}",
268 self.links.len(),
269 self.db_path.display()
270 );
271 }
272
273 Ok(())
274 }
275
276 /// Parses the addresses recorded by an [`UNUSED_HEADER`] line into the
277 /// stack order the allocator uses.
278 ///
279 /// The line lists them the way the C# store's free list reads — most
280 /// recently freed first — and the stack pops from its end, so the two are
281 /// reverses of each other.
282 fn parse_unused_header(addresses: &str) -> Vec<u32> {
283 let mut unused: Vec<u32> = addresses
284 .split_whitespace()
285 .filter_map(|address| address.parse().ok())
286 .collect();
287 unused.reverse();
288 unused
289 }
290
291 /// The freed-address stack to start from after a load.
292 ///
293 /// A database this version wrote records the stack, because the order
294 /// decides which address the next link gets and nothing in the list of
295 /// stored links implies it. A database written before this version (or by
296 /// hand) does not, so the addresses missing below the highest stored one
297 /// are recovered instead, lowest reused first — an order the file does at
298 /// least determine.
299 ///
300 /// Addresses that a hand-edited file records but that are in use, or that
301 /// sit above the highest stored link, are dropped: handing them out would
302 /// overwrite a link or leave a hole the allocator would hand out twice.
303 fn restore_unused(&self, recorded: Option<Vec<u32>>) -> Vec<u32> {
304 match recorded {
305 Some(recorded) => {
306 let mut seen = HashSet::new();
307 recorded
308 .into_iter()
309 .filter(|address| {
310 *address > 0
311 && *address < self.allocated
312 && !self.links.contains_key(address)
313 && seen.insert(*address)
314 })
315 .collect()
316 }
317 None => (1..self.allocated)
318 .filter(|address| !self.links.contains_key(address))
319 .rev()
320 .collect(),
321 }
322 }
323
324 /// Hands out the address of the next link, reusing a freed one first.
325 ///
326 /// This is `ResizableDirectMemoryLinks.AllocateLink` in the C#
327 /// implementation: an address is only taken from beyond the end of the
328 /// store when no freed one is left. Reuse is observable — it decides the
329 /// address a query reports for a link it creates — so the two
330 /// implementations have to agree on it.
331 fn allocate(&mut self) -> u32 {
332 match self.unused.pop() {
333 Some(address) => address,
334 None => {
335 self.allocated += 1;
336 self.allocated
337 }
338 }
339 }
340
341 /// Gives `address` back to the allocator.
342 ///
343 /// Freeing the highest allocated address shrinks the store rather than
344 /// growing the free list, and takes with it every freed address that has
345 /// become the new end — `ResizableDirectMemoryLinks.Delete` does exactly
346 /// this, which is why C# reuses the address of a link it just appended
347 /// before it reuses one freed earlier.
348 fn release(&mut self, address: u32) {
349 if address == 0 || address > self.allocated {
350 return;
351 }
352 if address < self.allocated {
353 self.unused.push(address);
354 return;
355 }
356 self.allocated = address - 1;
357 while let Some(position) = self
358 .unused
359 .iter()
360 .position(|&freed| freed == self.allocated)
361 {
362 self.unused.remove(position);
363 self.allocated -= 1;
364 }
365 }
366
367 /// Saves all links to the database file; an in-memory storage has none.
368 pub fn save(&self) -> Result<()> {
369 if self.is_in_memory() {
370 return Ok(());
371 }
372 // Write a new file next to the database and move it over the old one,
373 // instead of truncating the database and rewriting it in place: a
374 // process stopped in the middle of a save (Ctrl+C, a crash) then
375 // leaves the previous complete file, not a truncated one (issue #108).
376 // Nothing is synced to disk, so this does not survive a power loss.
377 let saving = saving_path(&self.db_path);
378 let file = File::create(&saving)
379 .with_context(|| format!("Failed to create database: {}", saving.display()))?;
380
381 let mut writer = BufWriter::new(file);
382
383 // The freed addresses first: which of them the next link gets is not
384 // implied by the links that follow, and reloading has to resume the
385 // allocator exactly where it stopped.
386 if !self.unused.is_empty() {
387 let recorded: Vec<String> = self
388 .unused
389 .iter()
390 .rev()
391 .map(|address| address.to_string())
392 .collect();
393 writeln!(writer, "{UNUSED_HEADER} {}", recorded.join(" "))?;
394 }
395
396 // Sort by index for consistent output
397 let mut links: Vec<_> = self.links.values().collect();
398 links.sort_by_key(|l| l.index);
399
400 for link in links {
401 if let Some(name) = self
402 .names
403 .get(&link.index)
404 .filter(|name| !needs_name_metadata(name))
405 {
406 writeln!(
407 writer,
408 "({} {} {} \"{}\")",
409 link.index, link.source, link.target, name
410 )?;
411 } else {
412 writeln!(writer, "({} {} {})", link.index, link.source, link.target)?;
413 }
414 }
415
416 // Names need not have rows. Controls use this versioned comment rather
417 // than inserting line breaks into the line-oriented row grammar.
418 let mut metadata = self
419 .names
420 .iter()
421 .filter(|(id, name)| !self.links.contains_key(*id) || needs_name_metadata(name))
422 .collect::<Vec<_>>();
423 metadata.sort_by_key(|(id, _)| **id);
424 for (id, name) in metadata {
425 writeln!(writer, "{}", name_metadata(*id, name))?;
426 }
427
428 writer.flush()?;
429 drop(writer);
430 std::fs::rename(&saving, &self.db_path)
431 .with_context(|| format!("Failed to replace database: {}", self.db_path.display()))?;
432
433 if self.trace {
434 crate::diagnostics::stderr!(
435 "[TRACE] Saved {} links to {}",
436 self.links.len(),
437 self.db_path.display()
438 );
439 }
440
441 Ok(())
442 }
443
444 /// Creates a new link and returns its ID
445 ///
446 /// The address is the one `allocate` hands out: a freed one
447 /// when the store has any, and only otherwise a fresh one past the end.
448 pub fn create(&mut self, source: u32, target: u32) -> u32 {
449 let id = self.allocate();
450
451 let link = Link::new(id, source, target);
452 self.links.insert(id, link);
453
454 if self.trace {
455 crate::diagnostics::stderr!("[TRACE] Created link: ({} {} {})", id, source, target);
456 }
457
458 id
459 }
460
461 /// Creates the link at `id`, as an empty `(id: 0 0)` link.
462 ///
463 /// Reaching a specific address means asking the allocator for links until
464 /// it hands that one out, and the ones it handed out on the way are freed
465 /// again — they were never asked for. This is `ILinksExtensions.EnsureCreated`
466 /// in the C# implementation:
467 ///
468 /// ```csharp
469 /// do { createdLink = creator(); createdLinks.Add(createdLink); }
470 /// while (createdLink != max);
471 /// for (var i = 0; i < createdLinks.Count; i++)
472 /// if (!nonExistentAddresses.Contains(createdLinks[i]))
473 /// links.Delete(createdLinks[i]);
474 /// ```
475 ///
476 /// Freeing them in the order they were created is what leaves the last one
477 /// on top of the free list, so it is the address the next created link
478 /// gets.
479 pub fn ensure_created(&mut self, id: u32) -> u32 {
480 if id == 0 || self.links.contains_key(&id) {
481 return id;
482 }
483
484 let mut passed_over = Vec::new();
485 loop {
486 let created = self.create(0, 0);
487 if created == id {
488 break;
489 }
490 passed_over.push(created);
491 }
492
493 for address in passed_over {
494 let _ = self.delete_raw(address);
495 }
496
497 if self.trace {
498 crate::diagnostics::stderr!("[TRACE] Ensured link: ({} 0 0)", id);
499 }
500
501 id
502 }
503
504 /// Gets a link by ID
505 pub fn get(&self, id: u32) -> Option<&Link> {
506 self.links.get(&id)
507 }
508
509 /// Checks if a link exists
510 pub fn exists(&self, id: u32) -> bool {
511 self.links.contains_key(&id)
512 }
513
514 /// Updates a link's source and target **without** applying any policy.
515 ///
516 /// This is the raw store operation, the equivalent of writing straight to
517 /// `UnitedMemoryLinks` in the C# implementation. [`LinkStorage::update`]
518 /// wraps it with the upstream uniqueness/usages decorators; use this method
519 /// when you are supplying your own decorator stack (or deliberately want
520 /// none).
521 pub fn update_raw(&mut self, id: u32, source: u32, target: u32) -> Result<Link> {
522 if let Some(before) = self.links.get(&id).copied() {
523 if self.trace {
524 crate::diagnostics::stderr!(
525 "[TRACE] Updating link {} from ({} {}) to ({} {})",
526 id,
527 before.source,
528 before.target,
529 source,
530 target
531 );
532 }
533 self.links.insert(id, Link::new(id, source, target));
534 Ok(before)
535 } else {
536 Err(LinkError::not_found(id).into())
537 }
538 }
539
540 /// Deletes a link by ID **without** applying any policy.
541 ///
542 /// The raw counterpart of [`LinkStorage::delete`]: it removes exactly the
543 /// requested link (and its name), leaving any link that referenced it
544 /// dangling.
545 pub fn delete_raw(&mut self, id: u32) -> Result<Link> {
546 // Also remove the name mapping
547 if let Some(name) = self.names.remove(&id) {
548 self.name_to_id.remove(&name);
549 }
550
551 if let Some(link) = self.links.remove(&id) {
552 self.release(id);
553 if self.trace {
554 crate::diagnostics::stderr!(
555 "[TRACE] Deleted link: ({} {} {})",
556 link.index,
557 link.source,
558 link.target
559 );
560 }
561 Ok(link)
562 } else {
563 Err(LinkError::not_found(id).into())
564 }
565 }
566
567 /// Updates a link's source and target through the upstream
568 /// `doublets` uniqueness and usages resolution stack.
569 ///
570 /// This mirrors the C# implementation, which always talks to a
571 /// `UnitedMemoryLinks` wrapped in
572 /// `DecorateWithAutomaticUniquenessAndUsagesResolution()`. Concretely: if
573 /// another link already holds `(source, target)`, every reference to `id`
574 /// is re-pointed at that link and `id` is deleted, instead of storing a
575 /// duplicate doublet.
576 ///
577 /// Returns the state the link was in before the operation. Use
578 /// [`LinkStorage::update_raw`] for the undecorated write.
579 pub fn update(&mut self, id: u32, source: u32, target: u32) -> Result<Link> {
580 self.update_observed(id, source, target, &mut |_, _| {})
581 }
582
583 /// [`LinkStorage::update`], reporting every change the decorator stack made.
584 ///
585 /// Resolving a duplicate doublet re-points and deletes other links, so one
586 /// call can produce several changes. Layers above the storage need to see
587 /// all of them — the C# implementation gets them for free because its
588 /// decorators forward to a `WriteHandler`:
589 ///
590 /// ```csharp
591 /// var result = _links.Update(restriction, substitution, (before, after) => { ... });
592 /// ```
593 ///
594 /// `observer` is that handler. A change with a null `after` is a deletion.
595 ///
596 /// The upstream resolver also reports the duplicate a link is merged into
597 /// as an unchanged `(before, before)` pair — a documented deviation from
598 /// C#, whose `LinksUniquenessResolver` reports nothing for it. That pair
599 /// is not a change, so it is not passed on, and `--changes` lists the same
600 /// records in both languages.
601 pub fn update_observed(
602 &mut self,
603 id: u32,
604 source: u32,
605 target: u32,
606 observer: ChangeObserver<'_>,
607 ) -> Result<Link> {
608 let before = *self
609 .links
610 .get(&id)
611 .ok_or_else(|| LinkError::not_found(id))?;
612 let mut resolved = (&mut *self).with_automatic_uniqueness_and_usages_resolution();
613 resolved
614 .update_by_with(
615 [id],
616 [id, source, target],
617 &mut |before: doublets::Link<u32>, after| {
618 let merged_into = before == after && before.index != id;
619 if !merged_into {
620 observer(Link::from(before), Link::from(after));
621 }
622 doublets::data::Flow::Continue
623 },
624 )
625 .map_err(LinkError::from)?;
626 Ok(before)
627 }
628
629 /// Deletes a link through the upstream `doublets` uniqueness and usages
630 /// resolution stack, cascading to every link that references it.
631 ///
632 /// This mirrors the C# implementation's
633 /// `DecorateWithAutomaticUniquenessAndUsagesResolution()` behaviour: the
634 /// link is reset to `(null, null)`, everything that still references it is
635 /// deleted first, and only then is the link itself removed. Cycles
636 /// terminate rather than recursing forever.
637 ///
638 /// Returns the state the requested link was in before the operation. Use
639 /// [`LinkStorage::delete_raw`] for the undecorated removal.
640 pub fn delete(&mut self, id: u32) -> Result<Link> {
641 self.delete_observed(id, &mut |_, _| {})
642 }
643
644 /// [`LinkStorage::delete`], reporting every change the decorator stack made.
645 ///
646 /// A cascading delete removes every link that still referenced `id`, so one
647 /// call can produce several changes; see [`LinkStorage::update_observed`].
648 pub fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
649 let before = *self
650 .links
651 .get(&id)
652 .ok_or_else(|| LinkError::not_found(id))?;
653 let mut resolved = (&mut *self).with_automatic_uniqueness_and_usages_resolution();
654 resolved
655 .delete_by_with([id], &mut |before, after| observe(observer, before, after))
656 .map_err(LinkError::from)?;
657 Ok(before)
658 }
659
660 /// Every stored link, ordered by address.
661 ///
662 /// The order is part of the contract, not an implementation detail: the
663 /// query processor enumerates links through this method, so an
664 /// unspecified order would make pattern matching — and with it the order
665 /// `--changes` reports and the order a cascading delete visits usages —
666 /// vary between runs of the very same query. `HashMap::values` is exactly
667 /// such an order, seeded randomly per process. Sorting reproduces what the
668 /// C# store does naturally: `UnitedMemoryLinks` walks allocated addresses
669 /// from `1` upwards.
670 pub fn all(&self) -> Vec<&Link> {
671 let mut links: Vec<&Link> = self.links.values().collect();
672 links.sort_unstable_by_key(|link| link.index);
673 links
674 }
675
676 /// Returns all links matching a query pattern
677 pub fn query(
678 &self,
679 index: Option<u32>,
680 source: Option<u32>,
681 target: Option<u32>,
682 ) -> Vec<&Link> {
683 if let Some(matched) = self.indexed_query(index, source, target) {
684 return matched;
685 }
686 self.links
687 .values()
688 .filter(|link| {
689 (index.is_none() || index == Some(link.index))
690 && (source.is_none() || source == Some(link.source))
691 && (target.is_none() || target == Some(link.target))
692 })
693 .collect()
694 }
695
696 /// Searches for a link with the given source and target.
697 ///
698 /// When several links share the pair, the lowest address wins, so the
699 /// result never depends on hash map iteration order.
700 pub fn search(&self, source: u32, target: u32) -> Option<u32> {
701 if let Some(index) = self.links.indexed() {
702 return index.search(source, target);
703 }
704 self.links
705 .values()
706 .filter(|link| link.source == source && link.target == target)
707 .map(|link| link.index)
708 .min()
709 }
710
711 /// Gets or creates a link with the given source and target.
712 ///
713 /// The two calls are fully qualified on purpose. [`LinkStorage`] also
714 /// implements the upstream [`Doublets`] trait — including *for
715 /// `&mut LinkStorage`*, so that a borrowed store can be decorated — and
716 /// inside an inherent `&mut self` method the receiver's type is exactly
717 /// `&mut LinkStorage`. Method resolution reaches the trait impl on the
718 /// reference before it derefs to the inherent impl, so a bare
719 /// `self.search(..)` silently resolves to [`Doublets::search`], which
720 /// interprets [`LinksConstants::any`](doublets::data::LinksConstants) as a
721 /// wildcard instead of matching it literally. Naming the inherent methods
722 /// keeps the exact-match semantics this function documents.
723 pub fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
724 if let Some(id) = Self::search(self, source, target) {
725 id
726 } else {
727 Self::create(self, source, target)
728 }
729 }
730
731 /// Formats a link for display
732 pub fn format(&self, link: &Link) -> String {
733 // Use name if available
734 let index_str = self
735 .names
736 .get(&link.index)
737 .cloned()
738 .unwrap_or_else(|| link.index.to_string());
739 let source_str = self
740 .names
741 .get(&link.source)
742 .cloned()
743 .unwrap_or_else(|| link.source.to_string());
744 let target_str = self
745 .names
746 .get(&link.target)
747 .cloned()
748 .unwrap_or_else(|| link.target.to_string());
749 format!("({} {} {})", index_str, source_str, target_str)
750 }
751
752 /// Formats a link as LiNo suitable for database export.
753 pub fn format_lino(&self, link: &Link) -> String {
754 format!(
755 "({}: {} {})",
756 self.format_lino_reference(link.index),
757 self.format_lino_reference(link.source),
758 self.format_lino_reference(link.target)
759 )
760 }
761
762 /// Returns all database links as sorted LiNo lines.
763 pub fn lino_lines(&self) -> Vec<String> {
764 let mut links: Vec<_> = self.all();
765 links.sort_by_key(|l| l.index);
766 links
767 .into_iter()
768 .map(|link| self.format_lino(link))
769 .collect()
770 }
771
772 /// Writes the complete database as LiNo.
773 pub fn write_lino_output<P: AsRef<Path>>(&self, path: P) -> Result<()> {
774 let path = path.as_ref();
775 let file = OpenOptions::new()
776 .write(true)
777 .create(true)
778 .truncate(true)
779 .open(path)
780 .with_context(|| format!("Failed to create LiNo output: {}", path.display()))?;
781
782 let mut writer = BufWriter::new(file);
783 for line in self.lino_lines() {
784 writeln!(writer, "{line}")?;
785 }
786 writer.flush()?;
787 Ok(())
788 }
789
790 /// Formats the structure of a link
791 pub fn format_structure(&self, id: u32) -> Result<String> {
792 let mut visited = HashSet::new();
793 self.format_structure_recursive(id, &mut visited)
794 }
795
796 /// Formats a source spine using explicit frames rather than call-stack depth.
797 fn format_structure_recursive(&self, id: u32, visited: &mut HashSet<u32>) -> Result<String> {
798 let mut store = self;
799 crate::structure_format::format_structure(
800 &mut store,
801 id,
802 visited,
803 |store, address| store.get(address).copied(),
804 |store, address| store.exists(address),
805 |store, address| Ok(store.format_lino_reference(address)),
806 )
807 }
808
809 /// Prints all links
810 pub fn print_all_links(&self) {
811 let mut links: Vec<_> = self.all();
812 links.sort_by_key(|l| l.index);
813 for link in links {
814 println!("{}", self.format(link));
815 }
816 }
817
818 /// Prints a change (before -> after)
819 pub fn print_change(&self, before: &Option<Link>, after: &Option<Link>) {
820 let before_text = before.map(|l| self.format(&l)).unwrap_or_default();
821 let after_text = after.map(|l| self.format(&l)).unwrap_or_default();
822 println!("({}) ({})", before_text, after_text);
823 }
824
825 // Named links functionality (corresponds to NamedLinks.cs)
826
827 /// Gets or creates a link with a name
828 pub fn get_or_create_named(&mut self, name: &str) -> u32 {
829 if let Some(&id) = self.name_to_id.get(name) {
830 id
831 } else {
832 // Create a self-referential link for the name
833 // Fully qualified for the same reason as in
834 // [`LinkStorage::get_or_create`]: the `Doublets` impl for
835 // `&mut LinkStorage` shadows the inherent `create`/`update`.
836 let id = Self::create(self, 0, 0);
837 Self::update(self, id, id, id).ok();
838 self.names.insert(id, name.to_string());
839 self.name_to_id.insert(name.to_string(), id);
840 if self.trace {
841 crate::diagnostics::stderr!("[TRACE] Created named link: {} => {}", name, id);
842 }
843 id
844 }
845 }
846
847 /// Sets the name for a link, taking it away from any other link that had it
848 pub fn set_name(&mut self, id: u32, name: &str) {
849 // Remove old name mapping if exists
850 if let Some(old_name) = self.names.remove(&id) {
851 self.name_to_id.remove(&old_name);
852 }
853 // A name belongs to one link at a time
854 if let Some(previous) = self.name_to_id.insert(name.to_string(), id) {
855 self.names.remove(&previous);
856 }
857 self.names.insert(id, name.to_string());
858 if self.trace {
859 crate::diagnostics::stderr!("[TRACE] Set name: {} => {}", id, name);
860 }
861 }
862
863 /// Gets the name of a link
864 pub fn get_name(&self, id: u32) -> Option<&String> {
865 self.names.get(&id)
866 }
867
868 /// Gets a link ID by name
869 pub fn get_by_name(&self, name: &str) -> Option<u32> {
870 self.name_to_id.get(name).copied()
871 }
872
873 /// Removes the name for a link
874 pub fn remove_name(&mut self, id: u32) {
875 if let Some(name) = self.names.remove(&id) {
876 self.name_to_id.remove(&name);
877 if self.trace {
878 crate::diagnostics::stderr!("[TRACE] Removed name: {} => {}", id, name);
879 }
880 }
881 }
882
883 /// Returns true if trace mode is enabled
884 pub fn is_trace_enabled(&self) -> bool {
885 self.trace
886 }
887
888 fn format_lino_reference(&self, id: u32) -> String {
889 self.names
890 .get(&id)
891 .map(|name| escape_lino_reference(name))
892 .unwrap_or_else(|| id.to_string())
893 }
894}