Skip to main content

kv_derive_impl/
from_mapping.rs

1use std::collections::{BTreeMap, HashMap};
2
3use crate::result::Result;
4
5/// Constructs the structure from a mapping such as [`std::collections::HashMap`].
6pub trait FromMapping: Sized {
7    fn from_mapping(mapping: impl Mapping) -> Result<Self>;
8}
9
10/// Abstracts concrete map types so that [`FromMapping`] could accept any of the implementors.
11pub trait Mapping {
12    fn get_value(&self, key: &str) -> Option<&str>;
13}
14
15/// Wraps another mapping so that the values are got from the prefixed keys.
16pub struct PrefixedMapping<T>(pub T, pub &'static str);
17
18impl<T: Mapping> Mapping for PrefixedMapping<T> {
19    fn get_value(&self, key: &str) -> Option<&str> {
20        self.0.get_value(&format!("{}{}", self.1, key))
21    }
22}
23
24macro_rules! impl_mapping {
25    ($type:ty) => {
26        impl Mapping for $type {
27            fn get_value(&self, key: &str) -> Option<&str> {
28                self.get(key).map(AsRef::as_ref)
29            }
30        }
31    };
32}
33
34impl_mapping!(HashMap<&str, &str>);
35impl_mapping!(HashMap<String, &str>);
36impl_mapping!(HashMap<&str, String>);
37impl_mapping!(HashMap<String, String>);
38impl_mapping!(&HashMap<&str, &str>);
39impl_mapping!(&HashMap<String, &str>);
40impl_mapping!(&HashMap<&str, String>);
41impl_mapping!(&HashMap<String, String>);
42
43impl_mapping!(BTreeMap<&str, &str>);
44impl_mapping!(BTreeMap<String, &str>);
45impl_mapping!(BTreeMap<&str, String>);
46impl_mapping!(BTreeMap<String, String>);
47impl_mapping!(&BTreeMap<&str, &str>);
48impl_mapping!(&BTreeMap<String, &str>);
49impl_mapping!(&BTreeMap<&str, String>);
50impl_mapping!(&BTreeMap<String, String>);