Skip to main content

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