Skip to main content

memory_serve/
manifest.rs

1use std::collections::HashMap;
2
3/// Maps asset routes to the routes they are served on, see
4/// [`MemoryServe::manifest`](crate::MemoryServe::manifest).
5///
6/// With hashed routes enabled, `/assets/index.css` maps to e.g.
7/// `/assets/index.3f9a1c2b7d84e6a0.css`. HTML files, and all assets when
8/// hashed routes are disabled, map to their plain route.
9#[derive(Debug, Clone, Default, PartialEq, Eq)]
10pub struct Manifest {
11    routes: HashMap<&'static str, String>,
12}
13
14impl Manifest {
15    pub(crate) fn new(routes: HashMap<&'static str, String>) -> Self {
16        Self { routes }
17    }
18
19    /// The route an asset is served on, `None` for unknown routes.
20    pub fn get(&self, route: &str) -> Option<&str> {
21        self.routes.get(route).map(String::as_str)
22    }
23
24    /// Iterate over all `(route, served route)` pairs.
25    pub fn iter(&self) -> impl Iterator<Item = (&'static str, &str)> {
26        self.routes.iter().map(|(k, v)| (*k, v.as_str()))
27    }
28
29    /// The number of assets in the manifest.
30    pub fn len(&self) -> usize {
31        self.routes.len()
32    }
33
34    /// Whether the manifest contains no assets.
35    pub fn is_empty(&self) -> bool {
36        self.routes.is_empty()
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::Manifest;
43    use std::collections::HashMap;
44
45    #[test]
46    fn lookup() {
47        let manifest = Manifest::new(HashMap::from([
48            ("/a.css", "/a.0123456789abcdef.css".to_string()),
49            ("/index.html", "/index.html".to_string()),
50        ]));
51
52        assert_eq!(manifest.get("/a.css"), Some("/a.0123456789abcdef.css"));
53        assert_eq!(manifest.get("/index.html"), Some("/index.html"));
54        assert_eq!(manifest.get("/missing"), None);
55        assert_eq!(manifest.len(), 2);
56        assert!(!manifest.is_empty());
57        assert!(Manifest::default().is_empty());
58
59        let mut pairs: Vec<_> = manifest.iter().collect();
60        pairs.sort();
61        assert_eq!(
62            pairs,
63            [
64                ("/a.css", "/a.0123456789abcdef.css"),
65                ("/index.html", "/index.html")
66            ]
67        );
68    }
69}