Skip to main content

mln_style/source/
list.rs

1use crate::source::Source;
2
3/// A style's sources in the order they were added, found by id. Ids are
4/// unique. A change to a source replaces its value, so two lists whose
5/// sources are the same by [`Source::ptr_eq`] hold the same sources.
6///
7/// A style has few sources, so a lookup is a scan.
8#[derive(Clone, Default)]
9pub struct SourceList(Vec<Source>);
10
11impl SourceList {
12    #[must_use]
13    pub fn len(&self) -> usize {
14        self.0.len()
15    }
16
17    #[must_use]
18    pub fn is_empty(&self) -> bool {
19        self.0.is_empty()
20    }
21
22    fn position(&self, id: &str) -> Option<usize> {
23        self.0.iter().position(|source| source.id() == id)
24    }
25
26    #[must_use]
27    pub fn get(&self, id: &str) -> Option<&Source> {
28        self.0.iter().find(|source| source.id() == id)
29    }
30
31    /// The sources, in the order they were added.
32    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Source> + ExactSizeIterator {
33        self.0.iter()
34    }
35
36    /// Replaces the source with `source`'s id in place, or adds it last.
37    pub(crate) fn set(&mut self, source: Source) {
38        match self.position(source.id()) {
39            Some(index) => self.0[index] = source,
40            None => self.0.push(source),
41        }
42    }
43
44    /// Removes the source `id`, keeping the others in order.
45    pub(crate) fn remove(&mut self, id: &str) -> Option<Source> {
46        self.position(id).map(|index| self.0.remove(index))
47    }
48}
49
50impl std::fmt::Debug for SourceList {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_list().entries(self.0.iter().map(Source::id)).finish()
53    }
54}