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
mod decoders;
mod map_fns;

pub use decoders::{
    and_then, boolean, fail, field, float, integer, json, list, map, option, serde, string,
    succeed, unsigned_integer, BoxDecoder,
};
pub use map_fns::*;

pub trait Decoder<'a, DecodesTo> {
    // OK, so theoretically this needs to store some functions & some collection of arguments.
    // Since functions need to be of differing lengths we probably need a trait rather than a struct
    // with different implementations for lenghts of arguments.
    //
    // Structs could probably be generic over the types of the arguments?
    //
    // Or alternatively all functions have to take a JSON.Value enum and do the decoding based on that.
    fn decode(&self, value: &serde_json::Value) -> Result<DecodesTo, DecodeError>;
}

#[derive(thiserror::Error, Debug, PartialEq)]
pub enum DecodeError {
    #[error("Could not find field {0} in {1}")]
    MissingField(String, String),
    #[error("Expected a {0} but found a {1}")]
    IncorrectType(String, String),
    #[error("Invalid integer: {0}")]
    InvalidInteger(String),
    #[error("Integer {0} was too big to decode as {1}")]
    IntegerOverflow(String, &'static str),
    #[error("Serde error: {0}")]
    SerdeError(String),
    #[error("Error: {0}")]
    Other(String),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, PartialEq)]
    struct TestStruct {
        field_one: String,
    }

    impl TestStruct {
        fn new(field_one: String) -> Self {
            TestStruct { field_one }
        }
    }

    #[test]
    fn decode_a_struct() {
        let decoder = map(TestStruct::new, field("field_one", string()));

        let json = serde_json::from_str(r#"{"field_one": "test"}"#).unwrap();

        assert_eq!(
            decoder.decode(&json),
            Ok(TestStruct {
                field_one: "test".to_string()
            })
        )
    }

    #[derive(Debug, PartialEq)]
    struct Test4Struct {
        field_one: String,
        field_two: i64,
        field_three: bool,
        field_four: f64,
    }

    impl Test4Struct {
        fn new(field_one: String, field_two: i64, field_three: bool, field_four: f64) -> Self {
            Test4Struct {
                field_one,
                field_two,
                field_three,
                field_four,
            }
        }
    }

    // TODO: HashMaps, Arrays etc.
    // TODO: failure cases.

    #[test]
    fn one_of_the_macro_map_fns() {
        let decoder = map4(
            Test4Struct::new,
            field("field_one", string()),
            field("field_two", integer()),
            field("field_three", boolean()),
            field("field_four", float()),
        );

        let json = serde_json::json!({"field_one": "test", "field_two": 10000, "field_three": true, "field_four": 1.0});

        assert_eq!(
            decoder.decode(&json),
            Ok(Test4Struct {
                field_one: "test".to_string(),
                field_two: 10000,
                field_three: true,
                field_four: 1.0
            })
        )
    }

    #[test]
    fn decoding_a_list() {
        let decoder = list::<_, Vec<_>>(string());

        let json = serde_json::json!(["one", "two", "three", "four"]);

        assert_eq!(
            decoder.decode(&json),
            Ok(vec![
                "one".to_string(),
                "two".to_string(),
                "three".to_string(),
                "four".to_string()
            ])
        )
    }

    #[test]
    fn decoding_opt_vec_opt() {
        let decoder = option(list::<_, Vec<_>>(option(string())));

        assert_eq!(
            decoder.decode(&serde_json::json!(["hello", null])),
            Ok(Some(vec![Some("hello".to_string()), None]))
        );
        assert_eq!(decoder.decode(&serde_json::json!(null)), Ok(None))
    }

    #[test]
    fn decode_using_serde() {}

    #[test]
    fn test_and_then() {
        let decoder = and_then(
            |s| {
                if s == "ok" {
                    succeed(Some(s))
                } else {
                    fail("Go Away")
                }
            },
            string(),
        );

        assert_eq!(
            decoder.decode(&serde_json::json!("ok")),
            Ok(Some("ok".to_string()))
        );

        assert_eq!(
            decoder.decode(&serde_json::json!("fail")),
            Err(DecodeError::Other("Go Away".into()))
        );
    }

    #[test]
    #[allow(clippy::unnecessary_cast)]
    fn decoding_integers() {
        assert_eq!(integer().decode(&serde_json::json!(1)), Ok(1 as i32));
        assert_eq!(integer().decode(&serde_json::json!(1)), Ok(1 as i64));
        assert_eq!(
            integer::<i8>().decode(&serde_json::json!(512)),
            Err(DecodeError::IntegerOverflow("512".to_string(), "i8"))
        );

        assert_eq!(
            unsigned_integer().decode(&serde_json::json!(1)),
            Ok(1 as u32)
        );
        assert_eq!(
            unsigned_integer().decode(&serde_json::json!(1)),
            Ok(1 as u64)
        );
        assert_eq!(
            unsigned_integer::<u8>().decode(&serde_json::json!(512)),
            Err(DecodeError::IntegerOverflow("512".to_string(), "u8"))
        );
    }
}