valico/json_dsl/
coercers.rs

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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
use serde_json::{Value, to_string, to_value};

use super::errors;

#[allow(dead_code)]
#[derive(Copy, Clone)]
pub enum PrimitiveType {
    String,
    I64,
    U64,
    F64,
    Boolean,
    Null,
    Array,
    Object,
    // Reserved for future use in Rustless
    File
}

pub type CoercerResult<T> = Result<T, super::super::ValicoErrors>;

pub trait Coercer: Send + Sync {
    fn get_primitive_type(&self) -> PrimitiveType;
    fn coerce(&self, &mut Value, &str) -> CoercerResult<Option<Value>>;
}

#[derive(Copy, Clone)]
pub struct StringCoercer;

impl Coercer for StringCoercer {
    fn get_primitive_type(&self) -> PrimitiveType { PrimitiveType::String }
    fn coerce(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        if val.is_string() {
            Ok(None)
        } else if val.is_number() {
            Ok(Some(to_value(&to_string(&val).unwrap()).unwrap()))
        } else {
            Err(vec![
                Box::new(errors::WrongType {
                    path: path.to_string(),
                    detail: "Can't coerce value to string".to_string()
                })
            ])
        }
    }
}

#[derive(Copy, Clone)]
pub struct I64Coercer;

impl Coercer for I64Coercer {
    fn get_primitive_type(&self) -> PrimitiveType { PrimitiveType::I64 }
    fn coerce(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        if val.is_i64() {
            return Ok(None)
        } else if val.is_u64() {
            let val = val.as_u64().unwrap();
            return Ok(Some(to_value(&(val as i64)).unwrap()));
        } else if val.is_f64() {
            let val = val.as_f64().unwrap();
            return Ok(Some(to_value(&(val as i64)).unwrap()));
        } else if val.is_string() {
            let val = val.as_str().unwrap();
            let converted: Option<i64> = val.parse().ok();
            match converted {
                Some(num) => Ok(Some(to_value(&num).unwrap())),
                None => Err(vec![
                    Box::new(errors::WrongType {
                        path: path.to_string(),
                        detail: "Can't coerce string value to i64".to_string()
                    })
                ])
            }
        } else {
            Err(vec![
                Box::new(errors::WrongType {
                    path: path.to_string(),
                    detail: "Can't coerce object value to i64".to_string()
                })
            ])
        }
    }
}

#[derive(Copy, Clone)]
pub struct U64Coercer;

impl Coercer for U64Coercer {
    fn get_primitive_type(&self) -> PrimitiveType { PrimitiveType::U64 }
    fn coerce(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        if val.is_u64() {
            return Ok(None)
        } else if val.is_i64() {
            let val = val.as_i64().unwrap();
            return Ok(Some(to_value(&(val as u64)).unwrap()));
        } else if val.is_f64() {
            let val = val.as_f64().unwrap();
            return Ok(Some(to_value(&(val as u64)).unwrap()));
        } else if val.is_string() {
            let val = val.as_str().unwrap();
            let converted: Option<u64> = val.parse().ok();
            match converted {
                Some(num) => Ok(Some(to_value(&num).unwrap())),
                None => Err(vec![
                    Box::new(errors::WrongType {
                        path: path.to_string(),
                        detail: "Can't coerce string value to u64".to_string()
                    })
                ])
            }
        } else {
            Err(vec![
                Box::new(errors::WrongType {
                    path: path.to_string(),
                    detail: "Can't coerce object value to u64".to_string()
                })
            ])
        }
    }
}

#[derive(Copy, Clone)]
pub struct F64Coercer;

impl Coercer for F64Coercer {
    fn get_primitive_type(&self) -> PrimitiveType { PrimitiveType::F64 }
    fn coerce(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        if val.is_f64() {
            return Ok(None)
        } else if val.is_i64() {
            let val = val.as_i64().unwrap();
            return Ok(Some(to_value(&(val as f64)).unwrap()));
        } else if val.is_u64() {
            let val = val.as_u64().unwrap();
            return Ok(Some(to_value(&(val as f64)).unwrap()));
        } else if val.is_string() {
            let val = val.as_str().unwrap();
            let converted: Option<f64> = val.parse().ok();
            match converted {
                Some(num) => Ok(Some(to_value(&num).unwrap())),
                None => Err(vec![
                    Box::new(errors::WrongType {
                        path: path.to_string(),
                        detail: "Can't coerce string value to f64".to_string()
                    })
                ])
            }
        } else {
            Err(vec![
                Box::new(errors::WrongType {
                    path: path.to_string(),
                    detail: "Can't coerce object value to f64".to_string()
                })
            ])
        }
    }
}

#[derive(Copy, Clone)]
pub struct BooleanCoercer;

impl Coercer for BooleanCoercer {
    fn get_primitive_type(&self) -> PrimitiveType { PrimitiveType::Boolean }
    fn coerce(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        if val.is_boolean() {
            Ok(None)
        } else if val.is_string() {
            let val = val.as_str().unwrap();
            if val == "true" {
                Ok(Some(Value::Bool(true)))
            } else if val == "false" {
                Ok(Some(Value::Bool(false)))
            } else {
                Err(vec![
                    Box::new(errors::WrongType {
                        path: path.to_string(),
                        detail: "Can't coerce this string value to boolean. Correct values are 'true' and 'false'".to_string()
                    })
                ])
            }
        } else {
            Err(vec![
                Box::new(errors::WrongType {
                    path: path.to_string(),
                    detail: "Can't coerce object to boolean".to_string()
                })
            ])
        }
    }
}

#[derive(Copy, Clone)]
pub struct NullCoercer;

impl Coercer for NullCoercer {
    fn get_primitive_type(&self) -> PrimitiveType { PrimitiveType::Null }
    fn coerce(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        if val.is_null() {
            Ok(None)
        } else if val.is_string() {
            let val = val.as_str().unwrap();
            if val == "" {
                Ok(Some(Value::Null))
            } else {
                Err(vec![
                    Box::new(errors::WrongType {
                        path: path.to_string(),
                        detail: "Can't coerce this string value to null. Correct value is only empty string".to_string()
                    })
                ])
            }
        } else {
            Err(vec![
                Box::new(errors::WrongType {
                    path: path.to_string(),
                    detail: "Can't coerce object to null".to_string()
                })
            ])
        }
    }
}

pub struct ArrayCoercer {
    sub_coercer: Option<Box<Coercer + Send + Sync>>,
    separator: Option<String>
}

impl ArrayCoercer {
    pub fn new() -> ArrayCoercer {
        ArrayCoercer {
            sub_coercer: None,
            separator: None
        }
    }

    pub fn encoded(separator: String) -> ArrayCoercer {
        ArrayCoercer {
            separator: Some(separator),
            sub_coercer: None
        }
    }

    pub fn encoded_of(separator: String, sub_coercer: Box<Coercer + Send + Sync>) -> ArrayCoercer {
        ArrayCoercer {
            separator: Some(separator),
            sub_coercer: Some(sub_coercer)
        }
    }

    pub fn of_type(sub_coercer: Box<Coercer + Send + Sync>) -> ArrayCoercer {
        ArrayCoercer {
            separator: None,
            sub_coercer: Some(sub_coercer)
        }
    }

    fn coerce_array(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        let array = val.as_array_mut().unwrap();
        if self.sub_coercer.is_some() {
            let sub_coercer = self.sub_coercer.as_ref().unwrap();
            let mut errors = vec![];
            for i in 0..array.len() {
                let item_path = [path, i.to_string().as_ref()].join("/");
                match sub_coercer.coerce(&mut array[i], item_path.as_ref()) {
                    Ok(Some(value)) => {
                        array.remove(i);
                        array.insert(i, value);
                    },
                    Ok(None) => (),
                    Err(err) => {
                        errors.extend(err);
                    }
                }
            }

            if errors.len() == 0 {
                Ok(None)
            } else {
                Err(errors)
            }
        } else {
            Ok(None)
        }
    }
}

impl Coercer for ArrayCoercer {
    fn get_primitive_type(&self) -> PrimitiveType { PrimitiveType::Array }

    fn coerce(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        if val.is_array() {
            self.coerce_array(val, path)
        } else if val.is_string() && self.separator.is_some() {
            let separator = self.separator.as_ref().unwrap();
            let string = val.as_str().unwrap();
            let mut array = Value::Array(
                string
                    .split(&separator[..])
                    .map(|s| Value::String(s.to_string()))
                    .collect::<Vec<Value>>()
            );
            try!(self.coerce_array(&mut array, path));
            Ok(Some(array))
        } else {
            Err(vec![
                Box::new(errors::WrongType {
                    path: path.to_string(),
                    detail: "Can't coerce object to array".to_string()
                })
            ])
        }
    }
}

#[derive(Copy, Clone)]
pub struct ObjectCoercer;

impl Coercer for ObjectCoercer {
    fn get_primitive_type(&self) -> PrimitiveType { PrimitiveType::Object }
    fn coerce(&self, val: &mut Value, path: &str) -> CoercerResult<Option<Value>> {
        if val.is_object() {
            Ok(None)
        } else {
            Err(vec![
                Box::new(errors::WrongType {
                    path: path.to_string(),
                    detail: "Can't coerce non-object value to the object type".to_string()
                })
            ])
        }
    }
}