jsonrpc_client_core/macros.rs
1// Copyright 2017 Amagicom AB.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9/// The main macro of this crate. Generates JSON-RPC 2.0 client structs with automatic serialization
10/// and deserialization. Method calls get correct types automatically.
11#[macro_export]
12macro_rules! jsonrpc_client {
13 (
14 $(#[$struct_attr:meta])*
15 pub struct $struct_name:ident {$(
16 $(#[$attr:meta])*
17 pub fn $method:ident(&mut $selff:ident $(, $arg_name:ident: $arg_ty:ty)*)
18 -> RpcRequest<$return_ty:ty>;
19 )*}
20 ) => (
21 $(#[$struct_attr])*
22 pub struct $struct_name<T: $crate::Transport> {
23 transport: T,
24 }
25
26 impl<T: $crate::Transport> $struct_name<T> {
27 /// Creates a new RPC client backed by the given transport implementation.
28 pub fn new(transport: T) -> Self {
29 $struct_name { transport }
30 }
31
32 $(
33 $(#[$attr])*
34 pub fn $method(&mut $selff $(, $arg_name: $arg_ty)*)
35 -> $crate::RpcRequest<$return_ty, T::Future>
36 {
37 let method = String::from(stringify!($method));
38 let params = expand_params!($($arg_name,)*);
39 $crate::call_method(&mut $selff.transport, method, params)
40 }
41 )*
42 }
43 )
44}
45
46/// Expands a variable list of parameters into its serializable form. Is needed to make the params
47/// of a nullary method equal to `[]` instead of `()` and thus make sure it serializes to `[]`
48/// instead of `null`.
49#[doc(hidden)]
50#[macro_export]
51macro_rules! expand_params {
52 () => ([] as [(); 0]);
53 ($($arg_name:ident,)+) => (($($arg_name,)+))
54}