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