Skip to main content

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