valitron 0.5.6

Valitron is an ergonomics, functional and configurable validator
Documentation
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! # define `Value`, `ValueMap` types
//! input data will be converted Value with Serialization,
//! and Value will be converted new output data with Deserialization
//!
//! In any rule, you should be comparing it with primitive type
//!
//! ## cmp
//! `Value` comparing and ordering with primitive type(`u8`,`u16`,`u32`,`u64`,`i8`,`i16`,`i32`,`i64`,`f32`,`f64`,`str`,`bool`,`String`)
//!
//! Example:
//! ```
//! # use valitron::Value;
//! # fn main() {
//! let mut value = Value::Uint8(10);
//! assert!(value == 10_u8);
//! assert!(value > 9_u8);
//! assert!(&value == 10_u8);
//! assert!(&value > 9_u8);
//! assert!(&mut value == 10_u8);
//! assert!(&mut value > 9_u8);
//! # }
//! ```

use std::{collections::BTreeMap, fmt::Display, mem};

use crate::register::{FieldName, FieldNames, Parser};

use self::float::{Float32, Float64};

mod cmp;
mod float;

/// # serialized resultant
///
/// All rust types will be serialized into this, contains nested structures.
///
/// This is [`Rule`], [`Rule`] implementation's basis.
///
/// [`Rule`]: crate::rule::Rule
#[derive(Debug, PartialEq, Eq, Clone, Ord, PartialOrd)]
pub enum Value {
    Uint8(u8),
    Int8(i8),
    Uint16(u16),
    Int16(i16),
    Uint32(u32),
    Int32(i32),
    Uint64(u64),
    Int64(i64),
    Float32(float::Float32),
    Float64(float::Float64),
    String(String),
    Unit,
    Boolean(bool),
    Char(char),
    Bytes(Vec<u8>),

    // fn unimplemented
    // i128 u128 unimplemented
    // ISize(isize), unimplemented
    // USize(usize), unimplemented
    // pointer, Raw pointer unimplemented
    #[doc(hidden)]
    Option(Box<Option<Value>>),

    #[doc(hidden)]
    Array(Vec<Value>),

    #[doc(hidden)]
    Tuple(Vec<Value>),

    #[doc(hidden)]
    TupleStruct(Vec<Value>),

    #[doc(hidden)]
    NewtypeStruct(Vec<Value>),

    #[doc(hidden)]
    Enum(&'static str, Vec<Value>),
    #[doc(hidden)]
    EnumUnit(&'static str),
    #[doc(hidden)]
    TupleVariant(&'static str, Vec<Value>),

    #[doc(hidden)]
    Map(BTreeMap<Value, Value>),

    #[doc(hidden)]
    StructKey(String),
    /// the BtreeMap key only be StructKey(_)
    #[doc(hidden)]
    Struct(BTreeMap<Value, Value>),

    #[doc(hidden)]
    StructVariantKey(String),
    /// the BtreeMap key only be StructVariantKey(_)
    #[doc(hidden)]
    StructVariant(&'static str, BTreeMap<Value, Value>),
}

/// contain full [`Value`] and cursor
///
/// [`Value`]: self::Value
pub struct ValueMap {
    pub(crate) value: Value,
    pub(crate) index: FieldNames,
}

pub trait FromValue {
    fn from_value(value: &mut ValueMap) -> Option<&mut Self>;
}

impl ValueMap {
    pub(crate) fn new(value: Value) -> Self {
        Self {
            value,
            index: FieldNames::default(),
        }
    }

    /// change index
    pub fn index(&mut self, index: FieldNames) {
        debug_assert!(
            self.value.get_with_names(&index).is_some(),
            "field `{}` is not exist",
            index.as_str()
        );

        self.index = index;
    }

    /// Takes the FieldNames out of the ValueMap
    pub fn take_index(&mut self) -> FieldNames {
        let mut x = FieldNames::default();
        mem::swap(&mut self.index, &mut x);
        x
    }

    pub(crate) fn as_index(&self) -> &FieldNames {
        &self.index
    }

    /// get current field value
    pub fn current(&self) -> Option<&Value> {
        self.value.get_with_names(&self.index)
    }

    /// get current field mutable value
    pub fn current_mut(&mut self) -> Option<&mut Value> {
        self.value.get_with_names_mut(&self.index)
    }

    /// get field value by field names
    pub fn get(&self, key: &FieldNames) -> Option<&Value> {
        self.value.get_with_names(key)
    }

    /// get field mutable value by field names
    pub fn get_mut(&mut self, key: &FieldNames) -> Option<&mut Value> {
        self.value.get_with_names_mut(key)
    }

    pub(crate) fn value(self) -> Value {
        self.value
    }
}

impl Value {
    /// get field value by field name
    pub fn get_with_name(&self, name: &FieldName) -> Option<&Value> {
        match (name, self) {
            (FieldName::Array(i), Value::Array(vec)) => vec.get(*i),
            (FieldName::Tuple(i), Value::Tuple(vec))
            | (FieldName::Tuple(i), Value::TupleStruct(vec))
            | (FieldName::Tuple(i), Value::NewtypeStruct(vec))
            | (FieldName::Tuple(i), Value::Enum(_, vec))
            | (FieldName::Tuple(i), Value::TupleVariant(_, vec)) => vec.get(*i as usize),
            (FieldName::Literal(str), Value::Struct(btree)) => {
                btree.get(&Value::StructKey(str.to_string()))
            }
            (FieldName::StructVariant(str), Value::StructVariant(_, btree)) => {
                btree.get(&Value::StructVariantKey(str.to_string()))
            }
            (FieldName::Option, Value::Option(val)) => val.as_ref().as_ref(),
            _ => None,
        }
    }

    /// get field value by field names
    pub fn get_with_names(&self, names: &FieldNames) -> Option<&Value> {
        let mut value = Some(self);
        let mut parser = Parser::new(names.as_str());
        loop {
            match parser.next_name() {
                Ok(Some(name)) => {
                    value = match value {
                        Some(v) => v.get_with_name(&name),
                        None => return None,
                    }
                }
                Ok(None) => break value,
                Err(e) => panic!("{e}"),
            }
        }
    }

    /// get field mutable value by field name
    pub fn get_with_name_mut(&mut self, name: &FieldName) -> Option<&mut Value> {
        match (name, self) {
            (FieldName::Array(i), Value::Array(vec)) => vec.get_mut(*i),
            (FieldName::Tuple(i), Value::Tuple(vec))
            | (FieldName::Tuple(i), Value::TupleStruct(vec))
            | (FieldName::Tuple(i), Value::NewtypeStruct(vec))
            | (FieldName::Tuple(i), Value::Enum(_, vec))
            | (FieldName::Tuple(i), Value::TupleVariant(_, vec)) => vec.get_mut(*i as usize),
            (FieldName::Literal(str), Value::Struct(btree)) => {
                btree.get_mut(&Value::StructKey(str.to_string()))
            }
            (FieldName::StructVariant(str), Value::StructVariant(_, btree)) => {
                btree.get_mut(&Value::StructVariantKey(str.to_string()))
            }
            (FieldName::Option, Value::Option(val)) => val.as_mut().as_mut(),
            _ => None,
        }
    }

    /// get field mutable value by field names
    pub fn get_with_names_mut(&mut self, names: &FieldNames) -> Option<&mut Value> {
        let mut value = Some(self);
        let mut parser = Parser::new(names.as_str());
        loop {
            match parser.next_name() {
                Ok(Some(name)) => {
                    value = match value {
                        Some(v) => v.get_with_name_mut(&name),
                        None => break None,
                    }
                }
                Ok(None) => break value,
                Err(e) => panic!("{e}"),
            }
        }
    }

    pub fn is_leaf(&self) -> bool {
        matches!(
            self,
            Self::Uint8(_)
                | Self::Uint16(_)
                | Self::Uint32(_)
                | Self::Uint64(_)
                | Self::Int8(_)
                | Self::Int16(_)
                | Self::Int32(_)
                | Self::Int64(_)
                | Self::Boolean(_)
                | Self::Char(_)
                | Self::Float32(_)
                | Self::Float64(_)
                | Self::Unit
                | Self::String(_)
        )
    }

    pub fn as_u8(&self) -> Option<&u8> {
        match self {
            Value::Uint8(u) => Some(u),
            _ => None,
        }
    }

    pub fn as_i8(&self) -> Option<&i8> {
        match self {
            Value::Int8(u) => Some(u),
            _ => None,
        }
    }

    pub fn as_u16(&self) -> Option<&u16> {
        match self {
            Value::Uint16(u) => Some(u),
            _ => None,
        }
    }

    pub fn as_i16(&self) -> Option<&i16> {
        match self {
            Value::Int16(u) => Some(u),
            _ => None,
        }
    }

    pub fn as_u32(&self) -> Option<&u32> {
        match self {
            Value::Uint32(u) => Some(u),
            _ => None,
        }
    }

    pub fn as_i32(&self) -> Option<&i32> {
        match self {
            Value::Int32(u) => Some(u),
            _ => None,
        }
    }

    pub fn as_u64(&self) -> Option<&u64> {
        match self {
            Value::Uint64(u) => Some(u),
            _ => None,
        }
    }

    pub fn as_i64(&self) -> Option<&i64> {
        match self {
            Value::Int64(u) => Some(u),
            _ => None,
        }
    }

    pub fn as_f32(&self) -> Option<&f32> {
        match self {
            Value::Float32(float::Float32(f)) => Some(f),
            _ => None,
        }
    }

    pub fn as_f32_mut(&mut self) -> Option<&mut f32> {
        match self {
            Value::Float32(float::Float32(f)) => Some(f),
            _ => None,
        }
    }

    pub fn as_f64(&self) -> Option<&f64> {
        match self {
            Value::Float64(float::Float64(f)) => Some(f),
            _ => None,
        }
    }

    pub fn as_f64_mut(&mut self) -> Option<&mut f64> {
        match self {
            Value::Float64(float::Float64(f)) => Some(f),
            _ => None,
        }
    }

    pub fn as_string(&self) -> Option<&String> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    pub fn as_boolean(&self) -> Option<&bool> {
        match self {
            Value::Boolean(b) => Some(b),
            _ => None,
        }
    }

    pub fn as_char(&self) -> Option<&char> {
        match self {
            Value::Char(c) => Some(c),
            _ => None,
        }
    }
}

impl FromValue for ValueMap {
    fn from_value(value: &mut ValueMap) -> Option<&mut Self> {
        Some(value)
    }
}

impl FromValue for Value {
    fn from_value(value: &mut ValueMap) -> Option<&mut Self> {
        value.current_mut()
    }
}

macro_rules! primitive_impl {
    ($($val:ident($ty:ty)),+) => {
        $(
            impl FromValue for $ty {
                fn from_value(value: &mut ValueMap) -> Option<&mut Self> {
                    if let Some(Value::$val(n)) = value.current_mut() {
                        Some(n)
                    } else {
                        None
                    }
                }
            }
        )+
    };
}

primitive_impl!(
    Uint8(u8),
    Int8(i8),
    Uint16(u16),
    Int16(i16),
    Uint32(u32),
    Int32(i32),
    Uint64(u64),
    Int64(i64),
    String(String),
    Boolean(bool),
    Char(char)
);

impl FromValue for f32 {
    fn from_value(value: &mut ValueMap) -> Option<&mut Self> {
        if let Some(Value::Float32(float::Float32(n))) = value.current_mut() {
            Some(n)
        } else {
            None
        }
    }
}

impl FromValue for f64 {
    fn from_value(value: &mut ValueMap) -> Option<&mut Self> {
        if let Some(Value::Float64(float::Float64(n))) = value.current_mut() {
            Some(n)
        } else {
            None
        }
    }
}

pub type Bytes = Vec<u8>;

impl FromValue for Bytes {
    fn from_value(value: &mut ValueMap) -> Option<&mut Bytes> {
        if let Some(Value::Bytes(bytes)) = value.current_mut() {
            Some(bytes)
        } else {
            None
        }
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Uint8(n) => n.fmt(f),
            Value::Int8(n) => n.fmt(f),
            Value::Uint16(n) => n.fmt(f),
            Value::Int16(n) => n.fmt(f),
            Value::Uint32(n) => n.fmt(f),
            Value::Int32(n) => n.fmt(f),
            Value::Uint64(n) => n.fmt(f),
            Value::Int64(n) => n.fmt(f),
            Value::Float32(Float32(n)) => n.fmt(f),
            Value::Float64(Float64(n)) => n.fmt(f),
            Value::String(n) => n.fmt(f),
            Value::Unit => "".fmt(f),
            Value::Boolean(n) => n.fmt(f),
            Value::Char(n) => n.fmt(f),
            _ => unreachable!("unsupported composite type"),
        }
    }
}