liquid_compiler/
registry.rs

1use std::collections::hash_map;
2
3type MapImpl<K, V> = hash_map::HashMap<K, V>;
4type KeysImpl<'a, K, V> = hash_map::Keys<'a, K, V>;
5
6/// Liquid language plugin registry.
7pub struct PluginRegistry<P> {
8    plugins: MapImpl<&'static str, P>,
9}
10
11impl<P> PluginRegistry<P> {
12    /// Create a new registry.
13    pub fn new() -> Self {
14        Self {
15            plugins: Default::default(),
16        }
17    }
18
19    /// Register a plugin
20    ///
21    /// Generally this is used when setting up the program.
22    ///
23    /// Returns whether this overrode an existing plugin.
24    pub fn register(&mut self, name: &'static str, plugin: P) -> bool {
25        let old = self.plugins.insert(name, plugin);
26        old.is_some()
27    }
28
29    /// Look up an existing plugin.
30    ///
31    /// Generally this is used for running plugins.
32    pub fn get(&self, name: &str) -> Option<&P> {
33        self.plugins.get(name)
34    }
35
36    /// All available plugins
37    pub fn plugin_names(&self) -> PluginNames<P> {
38        PluginNames {
39            iter: self.plugins.keys(),
40        }
41    }
42}
43
44impl<P> Default for PluginRegistry<P> {
45    #[inline]
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl<P> Clone for PluginRegistry<P>
52where
53    P: Clone,
54{
55    #[inline]
56    fn clone(&self) -> Self {
57        Self {
58            plugins: self.plugins.clone(),
59        }
60    }
61}
62
63//////////////////////////////////////////////////////////////////////////////
64
65macro_rules! delegate_iterator {
66    (($name:ident $($generics:tt)*) => $item:ty) => {
67        impl $($generics)* Iterator for $name $($generics)* {
68            type Item = $item;
69            #[inline]
70            fn next(&mut self) -> Option<Self::Item> {
71                self.iter.next().map(|s| *s)
72            }
73            #[inline]
74            fn size_hint(&self) -> (usize, Option<usize>) {
75                self.iter.size_hint()
76            }
77        }
78
79        impl $($generics)* ExactSizeIterator for $name $($generics)* {
80            #[inline]
81            fn len(&self) -> usize {
82                self.iter.len()
83            }
84        }
85    }
86}
87
88//////////////////////////////////////////////////////////////////////////////
89
90/// Available plugins.
91#[derive(Debug)]
92pub struct PluginNames<'a, P>
93where
94    P: 'a,
95{
96    iter: KeysImpl<'a, &'static str, P>,
97}
98
99delegate_iterator!((PluginNames<'a, P>) => &'static str);