Implement ToJson for all tuples

This commit is contained in:
Adolfo Ochagavía 2014-06-29 11:33:45 +02:00
parent 035914edcf
commit c3cf3b3fb1
1 changed files with 26 additions and 14 deletions

View File

@ -2015,25 +2015,37 @@ impl ToJson for String {
fn to_json(&self) -> Json { String((*self).clone()) } fn to_json(&self) -> Json { String((*self).clone()) }
} }
impl<A: ToJson, B: ToJson> ToJson for (A, B) { macro_rules! tuple_impl {
fn to_json(&self) -> Json { // use variables to indicate the arity of the tuple
match *self { ($($tyvar:ident),* ) => {
(ref a, ref b) => { // the trailing commas are for the 1 tuple
List(vec![a.to_json(), b.to_json()]) impl<
$( $tyvar : ToJson ),*
> ToJson for ( $( $tyvar ),* , ) {
#[inline]
#[allow(uppercase_variables)]
fn to_json(&self) -> Json {
match *self {
($(ref $tyvar),*,) => List(vec![$($tyvar.to_json()),*])
}
} }
} }
} }
} }
impl<A: ToJson, B: ToJson, C: ToJson> ToJson for (A, B, C) { tuple_impl!{A}
fn to_json(&self) -> Json { tuple_impl!{A, B}
match *self { tuple_impl!{A, B, C}
(ref a, ref b, ref c) => { tuple_impl!{A, B, C, D}
List(vec![a.to_json(), b.to_json(), c.to_json()]) tuple_impl!{A, B, C, D, E}
} tuple_impl!{A, B, C, D, E, F}
} tuple_impl!{A, B, C, D, E, F, G}
} tuple_impl!{A, B, C, D, E, F, G, H}
} tuple_impl!{A, B, C, D, E, F, G, H, I}
tuple_impl!{A, B, C, D, E, F, G, H, I, J}
tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
impl<'a, A: ToJson> ToJson for &'a [A] { impl<'a, A: ToJson> ToJson for &'a [A] {
fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) } fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }