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 deserialize_with with const generics #173

Merged
merged 1 commit into from
Mar 9, 2025
Merged
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
2 changes: 1 addition & 1 deletion jomini_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ serde_json = "1"
smallvec = { version = "1.13", features = ["serde", "union"] }

[dependencies]
syn = "2.0.81"
syn = { version = "2.0.81", features = ["derive"] }
quote = "1"
4 changes: 2 additions & 2 deletions jomini_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ pub fn derive(input: TokenStream) -> TokenStream {
duplicated: bool,
take_last: bool,
default: DefaultFallback,
deserialize_with: Option<Ident>,
deserialize_with: Option<syn::ExprPath>,
token: Option<u16>,
}

Expand Down Expand Up @@ -178,7 +178,7 @@ pub fn derive(input: TokenStream) -> TokenStream {

Ok(())
})
.expect("failed to parse binary token attribute");
.expect("failed to parse jomini attribute");
}

let attr = FieldAttr {
Expand Down
45 changes: 45 additions & 0 deletions jomini_derive/tests/15-const-generics.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use jomini_derive::JominiDeserialize;
use serde::Deserialize;

#[derive(JominiDeserialize, Debug)]
pub struct Model {
#[jomini(deserialize_with = "deserialize_array_with_length::<_, 5>")]
data: [u8; 5],
}

fn deserialize_array_with_length<'de, D, const N: usize>(
deserializer: D,
) -> Result<[u8; N], D::Error>
where
D: serde::Deserializer<'de>,
{
// This is a simple implementation that would parse a string of bytes
let s = String::deserialize(deserializer)?;
let bytes: Vec<u8> = s.bytes().collect();

if bytes.len() != N {
return Err(serde::de::Error::custom(format!(
"Expected array of length {}, got {}",
N,
bytes.len()
)));
}

let mut array = [0u8; N];
array.copy_from_slice(&bytes[..N]);
Ok(array)
}

#[test]
fn test_deserialize_with_const_generics() {
let json = r#"{"data":"hello"}"#;
let model: Model = serde_json::from_str(json).unwrap();
assert_eq!(model.data, [104, 101, 108, 108, 111]); // "hello" as bytes
}

#[test]
fn test_deserialize_with_const_generics_error() {
let json = r#"{"data":"hi"}"#;
let result: Result<Model, _> = serde_json::from_str(json);
assert!(result.is_err());
}