Require getters to return the correct type

This commit is contained in:
David Tolnay
2017-04-09 10:59:54 -07:00
parent a6d172111b
commit 9d8987bde8
3 changed files with 33 additions and 1 deletions
+6
View File
@@ -8,6 +8,12 @@ use self::content::{SerializeTupleVariantAsMapValue, SerializeStructVariantAsMap
#[cfg(feature = "std")]
use std::error;
/// Used to check that serde(getter) attributes return the expected type.
/// Not public API.
pub fn constrain<T: ?Sized>(t: &T) -> &T {
t
}
/// Not public API.
pub fn serialize_tagged_newtype<S, T>(serializer: S,
type_ident: &'static str,
+4 -1
View File
@@ -839,6 +839,9 @@ fn get_field<I>(params: &Parameters, field: &Field, ident: I) -> Tokens
let ident = ident.into();
quote!(&#self_var.#ident)
}
Some(getter) => quote!(&#getter(#self_var)),
Some(getter) => {
let ty = field.ty;
quote!(_serde::private::ser::constrain::<#ty>(&#getter(#self_var)))
}
}
}
@@ -0,0 +1,23 @@
#[macro_use]
extern crate serde_derive;
mod remote {
pub struct S {
a: u8,
}
impl S {
pub fn get(&self) -> u16 {
self.a as u16
}
}
}
#[derive(Serialize)] //~ ERROR: mismatched types
#[serde(remote = "remote::S")]
struct S {
#[serde(getter = "remote::S::get")]
a: u8, //~^^^^ expected u8, found u16
}
fn main() {}