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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use std::collections::hash_map;

type MapImpl<K, V> = hash_map::HashMap<K, V>;
type KeysImpl<'a, K, V> = hash_map::Keys<'a, K, V>;

/// Liquid language plugin registry.
pub struct PluginRegistry<P> {
    plugins: MapImpl<&'static str, P>,
}

impl<P> PluginRegistry<P> {
    /// Create a new registry.
    pub fn new() -> Self {
        Self {
            plugins: Default::default(),
        }
    }

    /// Register a plugin
    ///
    /// Generally this is used when setting up the program.
    ///
    /// Returns whether this overrode an existing plugin.
    pub fn register(&mut self, name: &'static str, plugin: P) -> bool {
        let old = self.plugins.insert(name, plugin);
        old.is_some()
    }

    /// Look up an existing plugin.
    ///
    /// Generally this is used for running plugins.
    pub fn get(&self, name: &str) -> Option<&P> {
        self.plugins.get(name)
    }

    /// All available plugins
    pub fn plugin_names(&self) -> PluginNames<P> {
        PluginNames {
            iter: self.plugins.keys(),
        }
    }
}

impl<P> Default for PluginRegistry<P> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<P> Clone for PluginRegistry<P>
where
    P: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            plugins: self.plugins.clone(),
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

macro_rules! delegate_iterator {
    (($name:ident $($generics:tt)*) => $item:ty) => {
        impl $($generics)* Iterator for $name $($generics)* {
            type Item = $item;
            #[inline]
            fn next(&mut self) -> Option<Self::Item> {
                self.iter.next().map(|s| *s)
            }
            #[inline]
            fn size_hint(&self) -> (usize, Option<usize>) {
                self.iter.size_hint()
            }
        }

        impl $($generics)* ExactSizeIterator for $name $($generics)* {
            #[inline]
            fn len(&self) -> usize {
                self.iter.len()
            }
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

/// Available plugins.
#[derive(Debug)]
pub struct PluginNames<'a, P>
where
    P: 'a,
{
    iter: KeysImpl<'a, &'static str, P>,
}

delegate_iterator!((PluginNames<'a, P>) => &'static str);