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