Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support #[serde(alias)] #567

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions rust/candid/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,14 @@ impl<'de> IDLDeserialize<'de> {
};
self.de.wire_type = ty.clone();

let mut v = T::deserialize(&mut self.de).with_context(|| {
let mut v = T::deserialize(&mut self.de).with_context(|| -> String {
if self.de.config.full_error_message
|| (text_size(&ty, MAX_TYPE_LEN).is_ok()
&& text_size(&expected_type, MAX_TYPE_LEN).is_ok())
{
format!("Fail to decode argument {ind} from {ty} to {expected_type}")
format!("Fail to decode argument {ind} from {ty} to {expected_type} when deserializing to {}", std::any::type_name::<T>())
} else {
format!("Fail to decode argument {ind}")
format!("Fail to decode argument {ind} when deserializing to {}", std::any::type_name::<T>())
}
});
if self.de.config.full_error_message {
Expand Down Expand Up @@ -985,8 +985,16 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.add_cost(1)?;
match (self.expect_type.as_ref(), self.wire_type.as_ref()) {
(TypeInner::Record(e), TypeInner::Record(w)) => {
let expect = e.clone().into();
let wire = w.clone().into();
// Remove expected keys that don't exist on the wire.
// Serde will still complain unless the user has explicitly allowed the field to not be populated.
let wire_keys = w.iter().cloned().map(|w| (w.id.get_id(), w)).collect::<std::collections::BTreeMap<_, _>>();
let kv = e.iter().filter_map(|e| {
let id = e.id.get_id();
wire_keys.get(&id).map(|wire| (id, (e.clone(), wire.clone())))}
).collect::<Vec<_>>();

let wire = kv.iter().map(|(_, (_, w))| w.clone()).collect::<VecDeque<Field>>();
let expect = kv.iter().map(|(_, (e, _))| e.clone()).collect::<VecDeque<Field>>();
let value =
visitor.visit_map(Compound::new(self, Style::Struct { expect, wire }))?;
Ok(value)
Expand Down
36 changes: 30 additions & 6 deletions rust/candid_derive/src/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,13 +277,15 @@ fn get_serde_meta_items(attr: &syn::Attribute) -> Result<Vec<syn::Meta>, ()> {

struct Attributes {
rename: Option<String>,
aliases: Vec<String>,
with_bytes: bool,
}

fn get_attrs(attrs: &[syn::Attribute]) -> Attributes {
use syn::Meta;
let mut res = Attributes {
rename: None,
aliases: Vec::new(),
with_bytes: false,
};
for item in attrs.iter().flat_map(get_serde_meta_items).flatten() {
Expand All @@ -310,6 +312,12 @@ fn get_attrs(attrs: &[syn::Attribute]) -> Attributes {
}
}
}
// #[serde(alias = "foo")]
Meta::NameValue(m) if m.path.is_ident("alias") => {
if let Ok(lit) = get_lit_str(&m.value) {
res.aliases.push(lit.value());
}
}
// #[serde(with = "serde_bytes")]
Meta::NameValue(m) if m.path.is_ident("with") => {
if let Ok(lit) = get_lit_str(&m.value) {
Expand All @@ -332,7 +340,7 @@ fn fields_from_ast(
let mut fs: Vec<_> = fields
.iter()
.enumerate()
.map(|(i, field)| {
.flat_map(|(i, field)| {
let attrs = get_attrs(&field.attrs);
let (real_ident, renamed_ident, hash) = match field.ident {
Some(ref ident) => {
Expand All @@ -351,13 +359,29 @@ fn fields_from_ast(
}
None => (Ident::Unnamed(i as u32), Ident::Unnamed(i as u32), i as u32),
};
Field {
real_ident,
let ty = derive_type(&field.ty, custom_candid_path);
let with_bytes = attrs.with_bytes;

// Create the main field
let main_field = Field {
real_ident: real_ident.clone(),
renamed_ident,
hash,
ty: derive_type(&field.ty, custom_candid_path),
with_bytes: attrs.with_bytes,
}
ty: ty.clone(),
with_bytes,
};

// Create alias fields
let alias_fields = attrs.aliases.into_iter().map(move |alias| Field {
real_ident: real_ident.clone(),
renamed_ident: Ident::Renamed(alias.clone()),
hash: idl_hash(&alias),
ty: ty.clone(),
with_bytes,
});

// Combine main field and alias fields
std::iter::once(main_field).chain(alias_fields)
})
.collect();
let unique: BTreeSet<_> = fs.iter().map(|Field { hash, .. }| hash).collect();
Expand Down
Loading