brush_core/
pathcache.rs

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