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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use crate::error::StructMapError;
use std::collections::HashMap;
use std::result::Result;
use std::vec::Vec;
pub use to_hash_map::*;

#[derive(Debug, Clone)]
pub enum FieldValue {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    String(String),
    Array(Vec<FieldValue>),
    Map(HashMap<String, FieldValue>),
}

impl ToString for FieldValue {
    fn to_string(&self) -> String {
        match self {
            FieldValue::Null => "".to_owned(),
            FieldValue::Bool(value) => value.to_string(),
            FieldValue::Int(value) => value.to_string(),
            FieldValue::Float(value) => value.to_string(),
            FieldValue::String(value) => value.to_string(),
            FieldValue::Array(value) => {
                let mut res = String::new();
                for val in value.iter() {
                    let v = val.to_string();
                    res.push_str(v.as_str());
                }
                res
            }
            FieldValue::Map(value) => {
                let mut res = String::new();
                for (key, val) in value {
                    res.push_str(key.as_str());
                    let v = val.to_string();
                    res.push_str(v.as_str());
                }
                res
            }
        }
    }
}

pub trait Converter: Sized {
    fn to_field_value(&self) -> FieldValue;
    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError>;
}

impl Converter for String {
    fn to_field_value(&self) -> FieldValue {
        FieldValue::String(self.to_string())
    }
    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::String(value) => Ok(value),
            _ => Err(StructMapError::new("invalid type: String")),
        }
    }
}

impl Converter for char {
    fn to_field_value(&self) -> FieldValue {
        FieldValue::String(self.to_string())
    }
    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::String(value) => {
                let chars: Vec<char> = value.chars().collect();
                if chars.len() != 1 {
                    return Err(StructMapError::new("invalid type: char"));
                }
                Ok(chars[0])
            }
            _ => Err(StructMapError::new("invalid type: char")),
        }
    }
}
impl Converter for bool {
    fn to_field_value(&self) -> FieldValue {
        FieldValue::Bool(*self)
    }

    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::Bool(value) => Ok(value),
            _ => Err(StructMapError::new("invalid type: bool")),
        }
    }
}

macro_rules! integer_impls {
    ($ ($type:ty) +) => {
        $(
            impl Converter for $type {
                #[inline]
                fn to_field_value(&self) -> FieldValue {
                    FieldValue::Int(*self as i64)
                }

                #[inline]
                fn to_primitive(fv: FieldValue) ->Result<Self, StructMapError> {
                    match fv {
                        FieldValue::Int(value)=>{
                            if let Ok(value) = <$type>::try_from(value) {
                                return Ok(value);
                            }
                            return Err(StructMapError::new(format!("invalid type: {}",stringify!($type).to_owned())))
                        },
                        _=> Err(StructMapError::new(format!("invalid type: {}",stringify!($type).to_owned()))),
                    }
                }
            }
        )+
    }
}

integer_impls!(i8 i16 i32 i64 isize u8 u16 u32);

impl Converter for f32 {
    fn to_field_value(&self) -> FieldValue {
        FieldValue::Float(*self as f64)
    }
    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::Float(value) => Ok(value as f32),
            _ => Err(StructMapError::new("invalid type: f32")),
        }
    }
}

impl Converter for f64 {
    fn to_field_value(&self) -> FieldValue {
        FieldValue::Float(*self)
    }
    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::Float(value) => Ok(value),
            _ => Err(StructMapError::new("invalid type: f64")),
        }
    }
}

impl<T> Converter for Option<T>
where
    T: Converter,
{
    fn to_field_value(&self) -> FieldValue {
        match self {
            Some(some) => some.to_field_value(),
            None => FieldValue::Null,
        }
    }

    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::Null => Ok(None),
            _ => Ok(Some(T::to_primitive(fv)?)),
        }
    }
}

impl<T> Converter for Vec<T>
where
    T: Converter,
{
    fn to_field_value(&self) -> FieldValue {
        FieldValue::Array(self.iter().map(|v| v.to_field_value()).collect())
    }

    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::Array(value) => value
                .into_iter()
                .map(|v| T::to_primitive(v))
                .collect::<Result<Vec<T>, StructMapError>>(),
            _ => Err(StructMapError::new("invalid type: Vec<T>")),
        }
    }
}

impl<K, V> Converter for HashMap<K, V>
where
    K: ToString + From<String> + std::cmp::Eq + std::hash::Hash,
    V: Converter,
{
    fn to_field_value(&self) -> FieldValue {
        FieldValue::Map(
            self.iter()
                .map(|(key, value)| (key.to_string(), value.to_field_value()))
                .collect(),
        )
    }

    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::Map(value) => {
                let mut result = HashMap::with_capacity(value.len());
                for (k, v) in value {
                    if let Ok(k) = K::try_from(k) {
                        result.insert(k, V::to_primitive(v)?);
                    } else {
                        return Err(StructMapError::new("invalid type: HashMap<K, V>"));
                    }
                }
                Ok(result)
            }
            _ => Err(StructMapError::new("invalid type: HashMap<K, V>")),
        }
    }
}

pub trait ToHashMap {
    fn to_map(&self) -> HashMap<String, FieldValue>;
    fn from_map(map: HashMap<String, FieldValue>) -> Result<Self, StructMapError>
    where
        Self: std::marker::Sized;
}

impl<T> Converter for T
where
    T: ToHashMap,
{
    fn to_field_value(&self) -> FieldValue {
        FieldValue::Map(self.to_map())
    }

    fn to_primitive(fv: FieldValue) -> Result<Self, StructMapError> {
        match fv {
            FieldValue::Map(value) => Ok(T::from_map(value)?),
            _ => Err(StructMapError::new("invalid type: Mapper")),
        }
    }
}