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    pub fn to_value(&self) -> Result<variables::ShellValue, error::Error> {
42        let pairs = self
43            .cache
44            .iter()
45            .map(|(k, v)| (Some(k.to_owned()), v.to_string_lossy().to_string()))
46            .collect::<Vec<_>>();
47
48        variables::ShellValue::associative_array_from_literals(variables::ArrayLiteral(pairs))
49    }
50
51    /// Removes the path associated with the given name, if there is one.
52    /// Returns whether or not an entry was removed.
53    ///
54    /// # Arguments
55    ///
56    /// * `name` - The name to remove.
57    pub fn unset<S: AsRef<str>>(&mut self, name: S) -> bool {
58        self.cache.remove(name.as_ref()).is_some()
59    }
60}