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
use std::error::Error;
use std::fmt;
use rustc_serialize::json::{self, Json};
pub trait FromResponse: Sized {
fn from_response(json: &Json) -> Result<Self, ParseError>;
#[allow(unused_variables)]
fn from_response_inherit(json: &Json, prev: &Self) -> Result<Self, ParseError> {
FromResponse::from_response(json)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseError {
ExpectedType(&'static str),
ExpectedFieldType(&'static str, &'static str),
ExpectedFieldValue(&'static str, &'static str),
UnexpectedField(&'static str),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ParseError::ExpectedType(t) =>
write!(f, "Expected response of type {}", t),
ParseError::ExpectedFieldType(k, t) =>
write!(f, "Expected field {} of type {}", k, t),
ParseError::ExpectedFieldValue(k, v) =>
write!(f, "Expected field {} to equal {}", k, v),
ParseError::UnexpectedField(k) =>
write!(f, "Unexpected field {}", k),
}
}
}
impl Error for ParseError {
fn description(&self) -> &str { "response parse error" }
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct JsonHelper<'a>(pub &'a Json);
impl<'a> JsonHelper<'a> {
pub fn as_object(&self) -> Result<JsonObjectHelper<'a>, ParseError>{
self.0.as_object()
.ok_or_else(|| ParseError::ExpectedType("object"))
.map(|o| JsonObjectHelper(o))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct JsonObjectHelper<'a>(pub &'a json::Object);
impl<'a> JsonObjectHelper<'a> {
pub fn get_string_option(&self, key: &'static str) -> Option<&'a str> {
self.0.get(key).and_then(Json::as_string)
}
pub fn get_string(&self, key: &'static str) -> Result<&'a str, ParseError> {
self.get_string_option(key).ok_or_else(|| ParseError::ExpectedFieldType(key, "string"))
}
pub fn get_i64_option(&self, key: &'static str) -> Option<i64> {
self.0.get(key).and_then(Json::as_i64)
}
pub fn get_i64(&self, key: &'static str) -> Result<i64, ParseError> {
self.get_i64_option(key).ok_or_else(|| ParseError::ExpectedFieldType(key, "i64"))
}
}