mail_template/
additional_cid.rs

1use std::collections::{
2    HashMap, HashSet
3};
4
5use serde::{Serialize, Serializer};
6
7use mail_core::Resource;
8use mail_headers::header_components::ContentId;
9
10pub struct AdditionalCIds<'a> {
11    additional_resources: &'a [&'a HashMap<String, Resource>]
12}
13
14impl<'a> AdditionalCIds<'a> {
15
16    /// Creates a new `AdditionalCIds` instance.
17    ///
18    /// All resources in the all hash maps have to be loaded to the
19    /// `Data` or `EncData` variants or using `get` can panic.
20    pub(crate) fn new(additional_resources: &'a [&'a HashMap<String, Resource>]) -> Self {
21        AdditionalCIds { additional_resources }
22    }
23
24
25    /// Returns the content id associated with the given name.
26    ///
27    /// If multiple of the maps used to create this type contain the
28    /// key the first match is returned and all later ones are ignored.
29    ///
30    /// # Panic
31    ///
32    /// If the resource exists but is not loaded (i.e. has no content id)
33    /// this will panic as this can only happen if there is a bug in the
34    /// mail code, or this type was used externally.
35    pub fn get(&self, name: &str) -> Option<&ContentId> {
36        for possible_source in self.additional_resources {
37            if let Some(res) = possible_source.get(name) {
38                return Some(res.content_id().expect("all resources should be loaded/have a content id"));
39            }
40        }
41        return None;
42    }
43}
44
45impl<'a> Serialize for AdditionalCIds<'a> {
46    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
47        where S: Serializer
48    {
49        let mut existing_keys = HashSet::new();
50        serializer.collect_map(
51            self.additional_resources
52            .iter()
53            .flat_map(|m| m.iter().map(|(k, resc)| {
54                (k, resc.content_id().expect("all resources should be loaded/have a content id"))
55            }))
56            .filter(|key| existing_keys.insert(key.to_owned()))
57        )
58    }
59}
60