1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use serde::{Deserialize, Serialize};
use std::{
    any::{type_name, Any, TypeId},
    collections::HashMap,
};

#[derive(Debug, Clone)]
pub enum PropsError {
    CouldNotReadData,
    HasNoDataOfType(String),
}

#[typetag::serde(tag = "type", content = "value")]
pub trait PropsData: std::fmt::Debug + Send + Sync {
    fn clone_props(&self) -> Box<dyn PropsData>;
    fn as_any(&self) -> &dyn Any;
}

impl Clone for Box<dyn PropsData> {
    fn clone(&self) -> Self {
        self.clone_props()
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct PropsDef(pub HashMap<String, Box<dyn PropsData>>);

#[derive(Debug, Default, Clone)]
pub struct Props(HashMap<TypeId, Box<dyn PropsData>>);

impl Props {
    pub(crate) fn from_raw(map: HashMap<TypeId, Box<dyn PropsData>>) -> Self {
        Self(map)
    }

    pub fn new<T>(data: T) -> Self
    where
        T: 'static + PropsData,
    {
        let mut result = HashMap::with_capacity(1);
        result.insert(TypeId::of::<T>(), Box::new(data) as Box<dyn PropsData>);
        Self(result)
    }

    pub fn has<T>(&self) -> bool
    where
        T: 'static + PropsData,
    {
        let e = TypeId::of::<T>();
        self.0.iter().any(|(t, _)| *t == e)
    }

    pub fn consume<T>(&mut self) -> Result<Box<dyn PropsData>, PropsError>
    where
        T: 'static + PropsData,
    {
        if let Some(v) = self.0.remove(&TypeId::of::<T>()) {
            Ok(v)
        } else {
            Err(PropsError::HasNoDataOfType(type_name::<T>().to_owned()))
        }
    }

    pub fn read<T>(&self) -> Result<&T, PropsError>
    where
        T: 'static + PropsData,
    {
        let e = TypeId::of::<T>();
        if let Some((_, v)) = self.0.iter().find(|(t, _)| **t == e) {
            if let Some(data) = v.as_any().downcast_ref::<T>() {
                Ok(data)
            } else {
                Err(PropsError::CouldNotReadData)
            }
        } else {
            Err(PropsError::HasNoDataOfType(type_name::<T>().to_owned()))
        }
    }

    pub fn map_or_default<T, R, F>(&self, mut f: F) -> R
    where
        T: 'static + PropsData,
        R: Default,
        F: FnMut(&T) -> R,
    {
        match self.read() {
            Ok(data) => f(data),
            Err(_) => R::default(),
        }
    }

    pub fn map_or_else<T, R, F, E>(&self, mut f: F, mut e: E) -> R
    where
        T: 'static + PropsData,
        F: FnMut(&T) -> R,
        E: FnMut() -> R,
    {
        match self.read() {
            Ok(data) => f(data),
            Err(_) => e(),
        }
    }

    pub fn read_cloned<T>(&self) -> Result<T, PropsError>
    where
        T: 'static + PropsData + Clone,
    {
        self.read::<T>().map(|v| v.clone())
    }

    pub fn read_cloned_or_default<T>(&self) -> T
    where
        T: 'static + PropsData + Clone + Default,
    {
        self.read_cloned().unwrap_or_default()
    }

    pub fn write<T>(&mut self, data: T)
    where
        T: 'static + PropsData,
    {
        self.0
            .insert(TypeId::of::<T>(), Box::new(data) as Box<dyn PropsData>);
    }

    pub fn with<T>(mut self, data: T) -> Self
    where
        T: 'static + PropsData,
    {
        self.write(data);
        self
    }

    pub fn without<T>(mut self) -> Self
    where
        T: 'static + PropsData,
    {
        self.0.remove(&TypeId::of::<T>());
        self
    }

    pub fn merge(self, other: Self) -> Self {
        let mut result = self.into_inner();
        result.extend(other.into_inner());
        Self(result)
    }

    pub(crate) fn into_inner(self) -> HashMap<TypeId, Box<dyn PropsData>> {
        self.0
    }
}

impl<T> From<T> for Props
where
    T: 'static + PropsData,
{
    fn from(data: T) -> Self {
        Self::new(data)
    }
}

impl From<&Self> for Props {
    fn from(data: &Self) -> Self {
        data.clone()
    }
}

#[macro_export]
macro_rules! implement_props_data {
    ($type_name:ty, $tag_name:literal) => {
        #[typetag::serde(name = $tag_name)]
        impl $crate::props::PropsData for $type_name
        where
            Self: Clone,
        {
            fn clone_props(&self) -> Box<dyn $crate::props::PropsData> {
                Box::new(self.clone())
            }

            fn as_any(&self) -> &dyn std::any::Any {
                self
            }
        }
    };
}

implement_props_data!((), "()");
implement_props_data!(i8, "i8");
implement_props_data!(i16, "i16");
implement_props_data!(i32, "i32");
implement_props_data!(i64, "i64");
implement_props_data!(i128, "i128");
implement_props_data!(u8, "u8");
implement_props_data!(u16, "u16");
implement_props_data!(u32, "u32");
implement_props_data!(u64, "u64");
implement_props_data!(u128, "u128");
implement_props_data!(f32, "f32");
implement_props_data!(f64, "f64");
implement_props_data!(bool, "bool");
implement_props_data!(String, "String");