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
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![warn(missing_docs)]
extern crate serde;
#[macro_use]
extern crate serde_derive;
pub extern crate serde_json;
#[cfg(feature = "base64-compat")]
pub extern crate base64;
pub mod client;
pub mod error;
mod util;
#[cfg(feature = "simple_http")]
pub mod simple_http;
pub use error::Error;
pub use client::{Client, Transport};
use serde_json::value::RawValue;
pub fn try_arg<T: serde::Serialize>(arg: T) -> Result<Box<RawValue>, serde_json::Error> {
RawValue::from_string(serde_json::to_string(&arg)?)
}
pub fn arg<T: serde::Serialize>(arg: T) -> Box<RawValue> {
match try_arg(arg) {
Ok(v) => v,
Err(e) => RawValue::from_string(format!("<<ERROR SERIALIZING ARGUMENT: {}>>", e))
.unwrap_or(RawValue::from_string("<<ERROR SERIALIZING ARGUMENT>>".to_owned()).unwrap()),
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Request<'a> {
pub method: &'a str,
pub params: &'a [Box<RawValue>],
pub id: serde_json::Value,
pub jsonrpc: Option<&'a str>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Response {
pub result: Option<Box<RawValue>>,
pub error: Option<error::RpcError>,
pub id: serde_json::Value,
pub jsonrpc: Option<String>,
}
impl Response {
pub fn result<T: for<'a> serde::de::Deserialize<'a>>(&self) -> Result<T, Error> {
if let Some(ref e) = self.error {
return Err(Error::Rpc(e.clone()));
}
if let Some(ref res) = self.result {
serde_json::from_str(res.get()).map_err(Error::Json)
} else {
serde_json::from_value(serde_json::Value::Null).map_err(Error::Json)
}
}
pub fn check_error(self) -> Result<(), Error> {
if let Some(e) = self.error {
Err(Error::Rpc(e))
} else {
Ok(())
}
}
pub fn is_none(&self) -> bool {
self.result.is_none()
}
}
#[cfg(test)]
mod tests {
use super::Response;
use serde_json;
use serde_json::value::RawValue;
#[test]
fn response_is_none() {
let joanna = Response {
result: Some(RawValue::from_string(serde_json::to_string(&true).unwrap()).unwrap()),
error: None,
id: From::from(81),
jsonrpc: Some(String::from("2.0")),
};
let bill = Response {
result: None,
error: None,
id: From::from(66),
jsonrpc: Some(String::from("2.0")),
};
assert!(!joanna.is_none());
assert!(bill.is_none());
}
#[test]
fn response_extract() {
let obj = vec!["Mary", "had", "a", "little", "lamb"];
let response = Response {
result: Some(RawValue::from_string(serde_json::to_string(&obj).unwrap()).unwrap()),
error: None,
id: serde_json::Value::Null,
jsonrpc: Some(String::from("2.0")),
};
let recovered1: Vec<String> = response.result().unwrap();
assert!(response.clone().check_error().is_ok());
let recovered2: Vec<String> = response.result().unwrap();
assert_eq!(obj, recovered1);
assert_eq!(obj, recovered2);
}
#[test]
fn null_result() {
let s = r#"{"result":null,"error":null,"id":"test"}"#;
let response: Response = serde_json::from_str(&s).unwrap();
let recovered1: Result<(), _> = response.result();
let recovered2: Result<(), _> = response.clone().result();
assert!(recovered1.is_ok());
assert!(recovered2.is_ok());
let recovered1: Result<String, _> = response.result();
let recovered2: Result<String, _> = response.clone().result();
assert!(recovered1.is_err());
assert!(recovered2.is_err());
}
#[test]
fn batch_response() {
let s = r#"[
{"jsonrpc": "2.0", "result": 7, "id": "1"},
{"jsonrpc": "2.0", "result": 19, "id": "2"},
{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "5"},
{"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
]"#;
let batch_response: Vec<Response> = serde_json::from_str(&s).unwrap();
assert_eq!(batch_response.len(), 5);
}
#[test]
fn test_arg() {
macro_rules! test_arg {
($val:expr, $t:ty) => {{
let val1: $t = $val;
let arg = super::arg(val1.clone());
let val2: $t = serde_json::from_str(arg.get()).expect(stringify!($val));
assert_eq!(val1, val2, "failed test for {}", stringify!($val));
}}
}
test_arg!(true, bool);
test_arg!(42, u8);
test_arg!(42, usize);
test_arg!(42, isize);
test_arg!(vec![42, 35], Vec<u8>);
test_arg!(String::from("test"), String);
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct Test {
v: String,
}
test_arg!(Test { v: String::from("test"), }, Test);
}
}