Skip to main content

shrub_core/
pathcache.rs

1//! Path cache
2
3use std::path::PathBuf;
4
5use crate::{error, variables};
6
7/// A cache of paths associated with names.
8#[derive(Clone, Default)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10pub struct PathCache {
11    /// The cache itself.
12    cache: std::collections::HashMap<String, PathBuf>,
13}
14
15impl PathCache {
16    /// Clears all elements from the cache.
17    pub fn reset(&mut self) {
18        self.cache.clear();
19    }
20
21    /// Returns the path associated with the given name.
22    ///
23    /// # Arguments
24    ///
25    /// * `name` - The name to lookup.
26    pub fn get<S: AsRef<str>>(&self, name: S) -> Option<PathBuf> {
27        self.cache.get(name.as_ref()).cloned()
28    }
29
30    /// Sets the path associated with the given name.
31    ///
32    /// # Arguments
33    ///
34    /// * `name` - The name to set.
35    /// * `path` - The path to associate with the name.
36    pub fn set<T: Into<String>>(&mut self, name: T, path: PathBuf) {
37        self.cache.insert(name.into(), path);
38    }
39
40    /// Projects the cache into a shell value.
41    ///
42    /// # Errors
43    ///
44    /// Returns any error from
45    /// [`variables::ShellValue::associative_array_from_literals`].
46    /// Cache entries always carry keys, so this does not fail in practice.
47    pub fn to_value(&self) -> Result<variables::ShellValue, error::Error> {
48        let pairs = self
49            .cache
50            .iter()
51            .map(|(k, v)| (Some(k.to_owned()), v.to_string_lossy().to_string()))
52            .collect::<Vec<_>>();
53
54        variables::ShellValue::associative_array_from_literals(variables::ArrayLiteral(pairs))
55    }
56
57    /// Removes the path associated with the given name, if there is one.
58    /// Returns whether or not an entry was removed.
59    ///
60    /// # Arguments
61    ///
62    /// * `name` - The name to remove.
63    pub fn unset<S: AsRef<str>>(&mut self, name: S) -> bool {
64        self.cache.remove(name.as_ref()).is_some()
65    }
66}