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
#![cfg(feature = "serdely")]
extern crate serde_json;

use super::{Validated, ValidatedWrapper};

use std::error::Error;
use std::fmt::{self, Display, Debug, Formatter};
use std::str::Utf8Error;
use std::ops::Deref;
use std::ops::DerefMut;
use std::hash::{Hash, Hasher};

use self::serde_json::Value;

#[derive(Debug, PartialEq, Clone)]
pub enum JSONArrayError {
    IncorrectJSONArray,
    UTF8Error(Utf8Error),
}

impl Display for JSONArrayError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl Error for JSONArrayError {}

pub type JSONArrayResult = Result<JSONArray, JSONArrayError>;

#[derive(Debug, PartialEq)]
pub struct JSONArrayValidator {}

#[derive(Clone)]
pub struct JSONArray {
    value: Value,
    full_json_array: String,
}

impl JSONArray {
    pub fn get_json_value(&self) -> &Value {
        &self.value
    }

    pub fn get_full_json_array(&self) -> &str {
        &self.full_json_array
    }

    pub fn into_vec(self) -> Vec<Value> {
        match self.value {
            Value::Array(array) => array,
            _ => unreachable!()
        }
    }

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

    pub fn into_string(self) -> String {
        self.full_json_array
    }
}

impl Deref for JSONArray {
    type Target = Vec<Value>;

    fn deref(&self) -> &Self::Target {
        self.value.as_array().unwrap()
    }
}

impl DerefMut for JSONArray {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.value.as_array_mut().unwrap()
    }
}

impl Validated for JSONArray {}

impl Debug for JSONArray {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Debug::fmt(&self.value, f)
    }
}

impl Display for JSONArray {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Display::fmt(&self.value, f)
    }
}

impl PartialEq for JSONArray {
    fn eq(&self, other: &Self) -> bool {
        self.full_json_array.eq(&other.full_json_array)
    }

    fn ne(&self, other: &Self) -> bool {
        self.full_json_array.ne(&other.full_json_array)
    }
}

impl Eq for JSONArray {}

impl Hash for JSONArray {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.full_json_array.hash(state)
    }
}

impl JSONArrayValidator {
    pub fn is_json_array(&self, full_json_array: &str) -> bool {
        self.parse_inner(full_json_array).is_ok()
    }

    pub fn parse_string(&self, full_json_array: String) -> JSONArrayResult {
        let mut json_array_inner = self.parse_inner(&full_json_array)?;

        json_array_inner.full_json_array = full_json_array;

        Ok(json_array_inner)
    }

    pub fn parse_str(&self, full_json_array: &str) -> JSONArrayResult {
        let mut json_array_inner = self.parse_inner(full_json_array)?;

        json_array_inner.full_json_array.push_str(full_json_array);

        Ok(json_array_inner)
    }

    fn parse_inner(&self, full_json_array: &str) -> JSONArrayResult {
        let json_array: Vec<Value> = match serde_json::from_str(full_json_array) {
            Ok(json_array) => json_array,
            Err(_) => return Err(JSONArrayError::IncorrectJSONArray)
        };

        let value = Value::Array(json_array);

        Ok(JSONArray {
            value,
            full_json_array: String::new(),
        })
    }
}

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

    #[test]
    fn test_json_array_lv1() {
        let json_array = "[1, \"Magic Len\"]".to_string();

        let jo = JSONArrayValidator {};

        jo.parse_string(json_array).unwrap();
    }
}

// JSONArray's wrapper struct is itself
impl ValidatedWrapper for JSONArray {
    type Error = JSONArrayError;

    fn from_string(json_array: String) -> Result<Self, Self::Error> {
        JSONArray::from_string(json_array)
    }

    fn from_str(json_array: &str) -> Result<Self, Self::Error> {
        JSONArray::from_str(json_array)
    }
}

impl JSONArray {
    pub fn from_string(full_json_array: String) -> Result<Self, JSONArrayError> {
        JSONArray::create_validator().parse_string(full_json_array)
    }

    pub fn from_str(full_json_array: &str) -> Result<Self, JSONArrayError> {
        JSONArray::create_validator().parse_str(full_json_array)
    }

    fn create_validator() -> JSONArrayValidator {
        JSONArrayValidator {}
    }
}


#[cfg(feature = "rocketly")]
impl<'a> ::rocket::request::FromFormValue<'a> for JSONArray {
    type Error = JSONArrayError;

    fn from_form_value(form_value: &'a ::rocket::http::RawStr) -> Result<Self, Self::Error> {
        JSONArray::from_string(form_value.url_decode().map_err(|err| JSONArrayError::UTF8Error(err))?)
    }
}

#[cfg(feature = "rocketly")]
impl<'a> ::rocket::request::FromParam<'a> for JSONArray {
    type Error = JSONArrayError;

    fn from_param(param: &'a ::rocket::http::RawStr) -> Result<Self, Self::Error> {
        JSONArray::from_string(param.url_decode().map_err(|err| JSONArrayError::UTF8Error(err))?)
    }
}

struct StringVisitor;

impl<'de> ::serde::de::Visitor<'de> for StringVisitor {
    type Value = JSONArray;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("an JSONArray string")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: ::serde::de::Error {
        JSONArray::from_str(v).map_err(|err| {
            E::custom(err.to_string())
        })
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: ::serde::de::Error {
        JSONArray::from_string(v).map_err(|err| {
            E::custom(err.to_string())
        })
    }
}

impl<'de> ::serde::Deserialize<'de> for JSONArray {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de> {
        deserializer.deserialize_string(StringVisitor)
    }
}

impl ::serde::Serialize for JSONArray {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer {
        self.value.serialize(serializer)
    }
}