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
//! # Helper trait for building a dynamic-language encode method

use base_encode::BaseEncode;
use core::RpType;
use dynamic_converter::DynamicConverter;
use errors::*;
use genco::Tokens;

pub trait DynamicEncode<'el>
where
    Self: DynamicConverter<'el>,
{
    fn name_encode(
        &self,
        input: Tokens<'el, Self::Custom>,
        name: Tokens<'el, Self::Custom>,
    ) -> Tokens<'el, Self::Custom>;

    fn array_encode(
        &self,
        input: Tokens<'el, Self::Custom>,
        inner: Tokens<'el, Self::Custom>,
    ) -> Tokens<'el, Self::Custom>;

    fn map_encode(
        &self,
        input: Tokens<'el, Self::Custom>,
        key: Tokens<'el, Self::Custom>,
        value: Tokens<'el, Self::Custom>,
    ) -> Tokens<'el, Self::Custom>;

    /// Handle the encoding of a datetime.
    fn datetime_encode(&self, input: Tokens<'el, Self::Custom>) -> Tokens<'el, Self::Custom> {
        input
    }

    fn dynamic_encode(
        &self,
        ty: &'el RpType,
        input: Tokens<'el, Self::Custom>,
    ) -> Result<Tokens<'el, Self::Custom>> {
        use self::RpType::*;

        if self.is_native(ty) {
            return Ok(input);
        }

        let stmt = match *ty {
            Signed { size: _ } | Unsigned { size: _ } => input,
            Float | Double => input,
            String => input,
            DateTime => self.datetime_encode(input),
            Any => input,
            Boolean => input,
            Name { ref name } => {
                let name = self.convert_type(name)?;
                self.name_encode(input, name)
            }
            Array { ref inner } => {
                let v = self.array_inner_var();
                let inner = self.dynamic_encode(inner, v)?;
                self.array_encode(input, inner)
            }
            Map { ref key, ref value } => {
                let map_key = self.map_key_var();
                let key = self.dynamic_encode(key, map_key)?;
                let map_value = self.map_value_var();
                let value = self.dynamic_encode(value, map_value)?;
                self.map_encode(input, key, value)
            }
            _ => input,
        };

        Ok(stmt)
    }
}

/// Dynamic encode is a valid decoding mechanism
impl<'el, T> BaseEncode<'el> for T
where
    T: DynamicEncode<'el>,
{
    fn base_encode(
        &self,
        ty: &'el RpType,
        input: Tokens<'el, Self::Custom>,
    ) -> Result<Tokens<'el, Self::Custom>> {
        self.dynamic_encode(ty, input)
    }
}