Skip to main content

link_cli/
named_types.rs

1//! Named type decorator for Rust link storage.
2//!
3//! This mirrors the C# `NamedTypesDecorator<uint>` role: link operations and
4//! pinned type access are delegated through `PinnedTypesDecorator`, while names
5//! are stored as external references in a separate links database.
6
7use std::path::{Path, PathBuf};
8
9use anyhow::Result;
10
11use crate::link::Link;
12use crate::link_storage::{ChangeObserver, LinkStorage};
13use crate::named_links::NamedLinks;
14use crate::pinned_types::{PinnedTypesAccess, PinnedTypesDecorator};
15
16pub trait NamedTypes {
17    fn get_name(&mut self, link: u32) -> Result<Option<String>>;
18    fn set_name(&mut self, link: u32, name: &str) -> Result<u32>;
19    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>>;
20    fn remove_name(&mut self, link: u32) -> Result<()>;
21}
22
23pub struct NamedTypesDecorator {
24    pinned_types_decorator: PinnedTypesDecorator,
25    names_links: LinkStorage,
26    trace: bool,
27}
28
29impl NamedTypesDecorator {
30    pub fn new<P>(database_filename: P, trace: bool) -> Result<Self>
31    where
32        P: AsRef<Path>,
33    {
34        let names_database_filename =
35            Self::make_names_database_filename(database_filename.as_ref());
36        Self::with_names_database_path(database_filename, names_database_filename, trace)
37    }
38
39    pub fn with_names_database_path<P, N>(
40        database_filename: P,
41        names_database_filename: N,
42        trace: bool,
43    ) -> Result<Self>
44    where
45        P: AsRef<Path>,
46        N: AsRef<Path>,
47    {
48        let database_path = path_to_string(database_filename.as_ref());
49        let names_database_path = path_to_string(names_database_filename.as_ref());
50        let links = LinkStorage::new(&database_path, trace)?;
51        let names_links = LinkStorage::new(&names_database_path, trace)?;
52        Ok(Self::from_link_storages_with_trace(
53            links,
54            names_links,
55            trace,
56        ))
57    }
58
59    pub fn from_link_storages(links: LinkStorage, names_links: LinkStorage) -> Self {
60        Self::from_link_storages_with_trace(links, names_links, false)
61    }
62
63    pub fn from_pinned_types_decorator(
64        pinned_types_decorator: PinnedTypesDecorator,
65        names_links: LinkStorage,
66    ) -> Self {
67        Self::from_decorators_with_trace(pinned_types_decorator, names_links, false)
68    }
69
70    /// Composes optional lookup-index decorators under both the data store and
71    /// Unicode names sidecar. Omit this builder to compare the original scans.
72    pub fn with_indexed_lookups(mut self) -> Self {
73        self.links_mut().enable_indexed_lookups();
74        self.names_links.enable_indexed_lookups();
75        self
76    }
77
78    pub fn make_names_database_filename<P>(database_filename: P) -> PathBuf
79    where
80        P: AsRef<Path>,
81    {
82        let path = database_filename.as_ref();
83        let filename_without_extension = path
84            .file_stem()
85            .and_then(|value| value.to_str())
86            .unwrap_or_default();
87        let names_filename = format!("{filename_without_extension}.names.links");
88
89        path.parent()
90            .filter(|parent| !parent.as_os_str().is_empty())
91            .map(|parent| parent.join(&names_filename))
92            .unwrap_or_else(|| PathBuf::from(names_filename))
93    }
94
95    pub fn links(&self) -> &LinkStorage {
96        self.pinned_types_decorator.links()
97    }
98
99    pub fn links_mut(&mut self) -> &mut LinkStorage {
100        self.pinned_types_decorator.links_mut()
101    }
102
103    pub fn pinned_types_decorator(&self) -> &PinnedTypesDecorator {
104        &self.pinned_types_decorator
105    }
106
107    pub fn pinned_types_decorator_mut(&mut self) -> &mut PinnedTypesDecorator {
108        &mut self.pinned_types_decorator
109    }
110
111    pub fn names_links(&self) -> &LinkStorage {
112        &self.names_links
113    }
114
115    pub fn names_links_mut(&mut self) -> &mut LinkStorage {
116        &mut self.names_links
117    }
118
119    pub(crate) fn query_copy(&self) -> Self {
120        Self::from_link_storages(self.links().query_copy(), self.names_links.query_copy())
121    }
122
123    pub fn into_link_storages(self) -> (LinkStorage, LinkStorage) {
124        (
125            self.pinned_types_decorator.into_link_storage(),
126            self.names_links,
127        )
128    }
129
130    pub fn save(&self) -> Result<()> {
131        self.pinned_types_decorator.save()?;
132        self.names_links.save()?;
133        Ok(())
134    }
135
136    pub fn create(&mut self, source: u32, target: u32) -> u32 {
137        self.pinned_types_decorator.create(source, target)
138    }
139
140    pub fn ensure_created(&mut self, id: u32) -> u32 {
141        self.pinned_types_decorator.ensure_created(id)
142    }
143
144    pub fn get(&self, id: u32) -> Option<&Link> {
145        self.pinned_types_decorator.get(id)
146    }
147
148    pub fn exists(&self, id: u32) -> bool {
149        self.pinned_types_decorator.exists(id)
150    }
151
152    pub fn update(&mut self, id: u32, source: u32, target: u32) -> Result<Link> {
153        self.update_observed(id, source, target, &mut |_, _| {})
154    }
155
156    /// See [`LinkStorage::update_raw`](crate::LinkStorage::update_raw).
157    pub fn update_raw(&mut self, id: u32, source: u32, target: u32) -> Result<Link> {
158        self.pinned_types_decorator.update_raw(id, source, target)
159    }
160
161    /// [`Self::update`], reporting every change the decorator stack made.
162    ///
163    /// Resolving a duplicate doublet deletes links, and a deleted link must not
164    /// keep its name. This mirrors the C# `NamedTypesDecorator.Update`, which
165    /// drops the name of every link the write handler reports as deleted:
166    ///
167    /// ```csharp
168    /// if (before != null && after == null)
169    /// {
170    ///     var deletedLinkIndex = _links.GetIndex(link: before);
171    ///     RemoveName(deletedLinkIndex);
172    /// }
173    /// ```
174    pub fn update_observed(
175        &mut self,
176        id: u32,
177        source: u32,
178        target: u32,
179        observer: ChangeObserver<'_>,
180    ) -> Result<Link> {
181        let mut deleted = Vec::new();
182        let updated = self.pinned_types_decorator.update_observed(
183            id,
184            source,
185            target,
186            &mut |before, after| {
187                if after.is_null() && !before.is_null() {
188                    deleted.push(before.index);
189                }
190                observer(before, after);
191            },
192        )?;
193        self.remove_names(&deleted)?;
194        Ok(updated)
195    }
196
197    pub fn delete(&mut self, id: u32) -> Result<Link> {
198        self.delete_observed(id, &mut |_, _| {})
199    }
200
201    /// [`Self::delete`], reporting every change the decorator stack made.
202    ///
203    /// A cascading delete removes every link that still referenced `id`; each of
204    /// them loses its name too, exactly as C# `NamedTypesDecorator.Delete` does.
205    pub fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
206        let mut deleted = Vec::new();
207        let removed = self
208            .pinned_types_decorator
209            .delete_observed(id, &mut |before, after| {
210                if after.is_null() && !before.is_null() {
211                    deleted.push(before.index);
212                }
213                observer(before, after);
214            })?;
215        if !deleted.contains(&id) {
216            deleted.push(id);
217        }
218        self.remove_names(&deleted)?;
219        Ok(removed)
220    }
221
222    fn remove_names(&mut self, indexes: &[u32]) -> Result<()> {
223        for index in indexes {
224            self.remove_name(*index)?;
225        }
226        Ok(())
227    }
228
229    pub fn all(&self) -> Vec<&Link> {
230        self.pinned_types_decorator.all()
231    }
232
233    pub fn query(
234        &self,
235        index: Option<u32>,
236        source: Option<u32>,
237        target: Option<u32>,
238    ) -> Vec<&Link> {
239        self.pinned_types_decorator.query(index, source, target)
240    }
241
242    pub fn search(&self, source: u32, target: u32) -> Option<u32> {
243        self.pinned_types_decorator.search(source, target)
244    }
245
246    pub fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
247        self.pinned_types_decorator.get_or_create(source, target)
248    }
249
250    fn from_link_storages_with_trace(
251        links: LinkStorage,
252        names_links: LinkStorage,
253        trace: bool,
254    ) -> Self {
255        Self::from_decorators_with_trace(
256            PinnedTypesDecorator::from_link_storage(links),
257            names_links,
258            trace,
259        )
260    }
261
262    fn from_decorators_with_trace(
263        pinned_types_decorator: PinnedTypesDecorator,
264        names_links: LinkStorage,
265        trace: bool,
266    ) -> Self {
267        Self {
268            pinned_types_decorator,
269            names_links,
270            trace,
271        }
272    }
273
274    pub(crate) fn logical_names(&mut self) -> Result<std::collections::BTreeMap<u32, String>> {
275        self.with_named_links(|named| named.unicode_storage().external_names())
276    }
277
278    fn with_named_links<T>(
279        &mut self,
280        action: impl FnOnce(&mut NamedLinks<'_>) -> Result<T>,
281    ) -> Result<T> {
282        let mut named_links = NamedLinks::new(&mut self.names_links)?;
283        action(&mut named_links)
284    }
285}
286
287impl NamedTypes for NamedTypesDecorator {
288    fn get_name(&mut self, link: u32) -> Result<Option<String>> {
289        if self.trace {
290            crate::diagnostics::stderr!("[TRACE] NamedTypesDecorator get_name for link {link}");
291        }
292        self.with_named_links(|named_links| named_links.get_name_by_external_reference(link))
293    }
294
295    fn set_name(&mut self, link: u32, name: &str) -> Result<u32> {
296        if self.trace {
297            crate::diagnostics::stderr!(
298                "[TRACE] NamedTypesDecorator set_name for link {link}: {name}"
299            );
300        }
301        if let Some(existing_link_with_name) = self.get_by_name(name)? {
302            if existing_link_with_name != link {
303                self.remove_name(existing_link_with_name)?;
304            }
305        }
306        self.remove_name(link)?;
307        self.with_named_links(|named_links| named_links.set_name_for_external_reference(link, name))
308    }
309
310    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
311        if self.trace {
312            crate::diagnostics::stderr!("[TRACE] NamedTypesDecorator get_by_name for name {name}");
313        }
314        self.with_named_links(|named_links| named_links.get_external_reference_by_name(name))
315    }
316
317    fn remove_name(&mut self, link: u32) -> Result<()> {
318        if self.trace {
319            crate::diagnostics::stderr!("[TRACE] NamedTypesDecorator remove_name for link {link}");
320        }
321        self.with_named_links(|named_links| named_links.remove_name_by_external_reference(link))
322    }
323}
324
325impl PinnedTypesAccess for NamedTypesDecorator {
326    fn pinned_types(&mut self, count: usize) -> Result<Vec<u32>> {
327        self.pinned_types_decorator.pinned_types(count)
328    }
329}
330
331fn path_to_string(path: &Path) -> String {
332    path.to_string_lossy().into_owned()
333}