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
#[macro_export]
macro_rules! mould_json {
([$($val:tt),*]) => {{
use $crate::rustc_serialize::json::{Json, Array};
let mut array = Array::new();
$( array.push(mould_json!($val)); )*
Json::Array(array)
}};
({ $($key:expr => $val:tt),* }) => {{
use $crate::rustc_serialize::json::{Json, Object};
let mut object = Object::new();
$( object.insert($key.to_owned(), mould_json!($val)); )*
Json::Object(object)
}};
($val:expr) => {{
use $crate::rustc_serialize::json::ToJson;
$val.to_json()
}};
}
#[macro_export]
macro_rules! mould_object {
{ $($key:expr => $val:tt),* } => {{
use $crate::rustc_serialize::json::Object;
let mut object = Object::new();
$( object.insert($key.to_owned(), mould_json!($val)); )*
object
}};
}
#[macro_export]
macro_rules! extract_field {
($request:ident, $name:expr) => {{
let opt = $request.extract($name);
try!(opt.ok_or_else(|| {
format!("Field {} not provided or have wrong format.", $name)
}))
}};
}
#[macro_export]
macro_rules! ensure_it {
($check:expr, $reason:expr) => {{
if !$check {
return Ok(::std::convert::From::from($reason.to_string()));
}
}};
}
mod test {
#[test]
fn test_json_plain() {
use rustc_serialize::json::{Json};
assert_eq!(Json::I64(1), mould_json!(1i64));
assert_eq!(Json::U64(2), mould_json!(2u64));
assert_eq!(Json::F64(3.1), mould_json!(3.1f64));
assert_eq!(Json::String("string".to_string()), mould_json!("string"));
assert_eq!(Json::Boolean(true), mould_json!(true));
assert_eq!(Json::Null, mould_json!(Json::Null));
}
#[test]
fn test_json_array() {
use rustc_serialize::json::{Json, Array};
let mut array = Array::new();
array.push(Json::I64(1));
array.push(Json::I64(2));
array.push(Json::I64(3));
array.push(Json::I64(4));
array.push(Json::I64(5));
assert_eq!(Json::Array(array), mould_json!([1i64,2,3,4,5]));
}
#[test]
fn test_json_object() {
use rustc_serialize::json::{Json, Object};
let mut object = Object::new();
object.insert("one".to_string(), Json::F64(3.1));
let mut inner = Object::new();
inner.insert("sub".to_string(), Json::String("string".to_string()));
object.insert("two".to_string(), Json::Object(inner));
assert_eq!(object, mould_object!{
"one" => 3.1f64,
"two" => (Json::Object(mould_object!{
"sub" => "string"
}))
});
assert_eq!(Json::Object(object), mould_json!({
"one" => 3.1f64,
"two" => (mould_json!({
"sub" => "string"
}))
}));
}
}