rschema_core/
definitions_map.rs

1use indexmap::IndexMap;
2
3use std::{
4    any::TypeId,
5    ops::{
6        Deref,
7        DerefMut,
8    },
9};
10
11use crate::{
12    Definitions,
13    Schematic,
14    Type,
15};
16
17type DefsMapItem = (&'static str, Type);
18type InnerMap = IndexMap<TypeId, DefsMapItem>;
19
20#[derive(Debug)]
21pub struct DefinitionsMap(InnerMap);
22
23impl Deref for DefinitionsMap {
24    type Target = InnerMap;
25
26    fn deref(&self) -> &Self::Target {
27        &self.0
28    }
29}
30
31impl DerefMut for DefinitionsMap {
32    fn deref_mut(&mut self) -> &mut Self::Target {
33        &mut self.0
34    }
35}
36
37impl IntoIterator for DefinitionsMap {
38    type Item = (TypeId, DefsMapItem);
39    type IntoIter = indexmap::map::IntoIter<TypeId, DefsMapItem>;
40
41    fn into_iter(self) -> Self::IntoIter {
42        self.0.into_iter()
43    }
44}
45
46impl DefinitionsMap {
47    pub fn new() -> Self {
48        Self(IndexMap::new())
49    }
50
51    pub fn insert<T: 'static + Schematic>(
52        &mut self,
53        name: &'static str,
54        def: Type,
55    ) {
56        let id = TypeId::of::<T>();
57        self.entry(id).or_insert((name, def));
58    }
59
60    pub fn extend_ty<T: Schematic>(&mut self) {
61        let definitions_map = <T as Schematic>::__defs_map();
62        self.extend(definitions_map);
63    }
64
65    pub fn build(self) -> Definitions {
66        Definitions::from_iter(self.0.into_values())
67    }
68}