Skip to content

Commit

Permalink
Add support for raw identifiers for the derive macro (#17)
Browse files Browse the repository at this point in the history
Closes #15
  • Loading branch information
droundy committed Jun 14, 2024
1 parent 51c7bd2 commit 3935f25
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
1 change: 1 addition & 0 deletions serde_avro_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
lazy_static = "1"
pretty_assertions = "1"
regex = "1"
serde = "1"
serde_json = "1"

[lints]
Expand Down
52 changes: 52 additions & 0 deletions serde_avro_derive/tests/derive_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,3 +416,55 @@ fn name_override() {
}"#,
);
}

#[test]
fn raw_identifiers() {
#[derive(BuildSchema, serde::Serialize, serde::Deserialize)]
#[avro_schema(name = Name, namespace = "namespace")]
#[allow(unused)]
struct Test {
r#inner: i32,
r#type: String,
}

test::<Test>(
r#"{
"type": "record",
"name": "namespace.Name",
"fields": [
{
"name": "inner",
"type": "int"
},
{
"name": "type",
"type": "string"
}
]
}"#,
);

let x = Test {
inner: 5,
r#type: "test".to_string(),
};

// Make sure serialization & deserialization both work in this scenario
let schema = &Test::schema().unwrap();
let _: Test = serde_avro_fast::from_datum_slice(
&serde_avro_fast::to_datum_vec(
&x,
&mut serde_avro_fast::ser::SerializerConfig::new(schema),
)
.unwrap(),
schema,
)
.unwrap();

// The following confirms that "raw" identifiers should be equivalent to their
// non-raw counterparts, as documented at
// https://doc.rust-lang.org/reference/identifiers.html#raw-identifiers Raw
// identifiers may either be a strange way to write an "ordinary" identifier,
// or may be the only way to use a keyword as an identifier.
assert_eq!(x.inner, 5);
}
3 changes: 2 additions & 1 deletion serde_avro_derive_macros/src/build_schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use {
quote::{format_ident, quote},
std::borrow::Cow,
syn::{
ext::IdentExt as _,
parse_quote, parse_quote_spanned,
visit::{self, Visit},
visit_mut::{self, VisitMut},
Expand Down Expand Up @@ -151,7 +152,7 @@ pub(crate) fn schema_impl(input: SchemaDeriveInput) -> Result<TokenStream, Error
.ok_or_else(|| {
Error::new(Span::call_site(), "Unnamed fields are not supported")
})?;
let field_names = field_idents.iter().map(|ident| ident.to_string());
let field_names = field_idents.iter().map(|ident| ident.unraw().to_string());

let has_non_lifetime_generics;
(type_lookup, type_lookup_decl, has_non_lifetime_generics) =
Expand Down

0 comments on commit 3935f25

Please sign in to comment.