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