1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use std::borrow;
use std::collections::HashMap;

use super::PartialSource;

/// In-memory collection of partial-template source code.
#[derive(Debug, Default, Clone)]
pub struct InMemorySource {
    data: HashMap<String, String>,
}

impl InMemorySource {
    /// Create an in-memory repository to store partial-template source.
    pub fn new() -> Self {
        Default::default()
    }

    /// Add a partial-template's souce.
    pub fn add<N, S>(&mut self, name: N, source: S) -> bool
    where
        N: Into<String>,
        S: Into<String>,
    {
        self.data.insert(name.into(), source.into()).is_some()
    }
}

impl PartialSource for InMemorySource {
    fn contains(&self, name: &str) -> bool {
        self.data.contains_key(name)
    }

    fn names(&self) -> Vec<&str> {
        self.data.keys().map(|s| s.as_str()).collect()
    }

    fn try_get<'a>(&'a self, name: &str) -> Option<borrow::Cow<'a, str>> {
        self.data.get(name).map(|s| s.as_str().into())
    }
}