-
Notifications
You must be signed in to change notification settings - Fork 18
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
Add SerializeBits
/DeserializeBits
derive macros
#84
Merged
Merged
Changes from 8 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ce28257
Rough serde support; padding and reserved don't play nice yet.
widberg 5a8bff4
Handle and test reserved and padding fields
widberg 3448ced
Deduplicate code in Deserialize and add more tests
widberg b66760b
Don't generate visit_map for unnamed fields
widberg d54a4fc
Fix serde feature being misconfigured in the Cargo.tomls
widberg 4c0a846
Use my git repo for arbitrary-int until pr gets merged
widberg 11cd1a3
Don't pin serde and serde_test patch versions of dev-dependencies
widberg 489ee75
Switch from git to crates.io for arbitrary-int
widberg 0d014aa
Improve serde tests
widberg c3911b8
Make unzip prettier
widberg 8913a40
Lint and test with serde in ci
widberg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,226 @@ | ||
use itertools::multiunzip; | ||
use proc_macro2::{Ident, TokenStream}; | ||
use proc_macro_error::abort_call_site; | ||
use quote::quote; | ||
use syn::{Data, Field, Fields}; | ||
|
||
use crate::shared::{self, unreachable}; | ||
|
||
fn filter_not_reserved_or_padding(field: &&Field) -> bool { | ||
let field_name_string = field.ident.as_ref().unwrap().to_string(); | ||
!field_name_string.starts_with("reserved_") && !field_name_string.starts_with("padding_") | ||
} | ||
|
||
pub(super) fn serialize_bits(item: TokenStream) -> TokenStream { | ||
let derive_input = shared::parse_derive(item); | ||
let name = &derive_input.ident; | ||
let name_str = name.to_string(); | ||
let struct_data = match derive_input.data { | ||
Data::Struct(s) => s, | ||
Data::Enum(_) => abort_call_site!("use derive(Serialize) for enums"), | ||
Data::Union(_) => unreachable(()), | ||
}; | ||
|
||
let serialize_impl = match struct_data.fields { | ||
Fields::Named(fields) => { | ||
let calls = fields.named.iter().filter(filter_not_reserved_or_padding).map(|f| { | ||
// We can unwrap since this is a named field | ||
let call = f.ident.as_ref().unwrap(); | ||
let name = call.to_string(); | ||
quote!(state.serialize_field(#name, &self.#call())?;) | ||
}); | ||
let len = fields.named.iter().filter(filter_not_reserved_or_padding).count(); | ||
quote! { | ||
use ::serde::ser::SerializeStruct; | ||
let mut state = serializer.serialize_struct(#name_str, #len)?; | ||
// state.serialize_field("field1", &self.field1())?; state.serialize_field("field2", &self.field2())?; state.serialize_field("field3", &self.field3())?; state.end() | ||
#(#calls)* | ||
state.end() | ||
} | ||
} | ||
Fields::Unnamed(fields) => { | ||
let calls = fields.unnamed.iter().enumerate().map(|(i, _)| { | ||
let call: Ident = syn::parse_str(&format!("val_{}", i)).unwrap_or_else(unreachable); | ||
quote!(state.serialize_field(&self.#call())?;) | ||
}); | ||
let len = fields.unnamed.len(); | ||
quote! { | ||
use serde::ser::SerializeTupleStruct; | ||
let mut state = serializer.serialize_tuple_struct(#name_str, #len)?; | ||
// state.serialize_field(&self.val0())?; state.serialize_field(&self.val1())?; state.end() | ||
#(#calls)* | ||
state.end() | ||
} | ||
} | ||
Fields::Unit => todo!("this is a unit struct, which is not supported right now"), | ||
}; | ||
|
||
quote! { | ||
impl ::serde::Serialize for #name { | ||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> | ||
where | ||
S: ::serde::Serializer, | ||
{ | ||
#serialize_impl | ||
} | ||
} | ||
} | ||
} | ||
|
||
fn deserialize_field_parts( | ||
i: usize, field_ident: &Ident, | ||
) -> ( | ||
TokenStream, | ||
TokenStream, | ||
TokenStream, | ||
TokenStream, | ||
TokenStream, | ||
TokenStream, | ||
TokenStream, | ||
String, | ||
) { | ||
let field_name_string = field_ident.to_string(); | ||
( | ||
quote!(#field_ident,), | ||
quote!(#field_name_string => Ok(Field::#field_ident),), | ||
quote!(#field_name_string,), | ||
quote!(let #field_ident = seq.next_element()?.ok_or_else(|| ::serde::de::Error::invalid_length(#i, &self))?;), | ||
quote!(let mut #field_ident = None;), | ||
quote!(Field::#field_ident => { | ||
if #field_ident.is_some() { | ||
return Err(::serde::de::Error::duplicate_field(#field_name_string)); | ||
} | ||
#field_ident = Some(map.next_value()?); | ||
}), | ||
quote!(let #field_ident = #field_ident.ok_or_else(|| ::serde::de::Error::missing_field(#field_name_string))?;), | ||
format!("`{}`", field_name_string), | ||
) | ||
} | ||
|
||
pub(super) fn deserialize_bits(item: TokenStream) -> TokenStream { | ||
let derive_input = shared::parse_derive(item); | ||
let name = &derive_input.ident; | ||
let name_str = name.to_string(); | ||
let struct_name_str = format!("struct {}", name_str); | ||
let struct_data = match derive_input.data { | ||
Data::Struct(s) => s, | ||
Data::Enum(_) => abort_call_site!("use derive(Serialize) for enums"), | ||
Data::Union(_) => unreachable(()), | ||
}; | ||
|
||
let should_have_visit_map = matches!(struct_data.fields, Fields::Named(_)); | ||
|
||
let ( | ||
field_names, | ||
field_deserialize, | ||
field_name_strings, | ||
field_visit_seq, | ||
field_visit_map_init, | ||
field_visit_map_match, | ||
field_visit_map_check, | ||
mut field_expecting, | ||
): (Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>) = match struct_data.fields { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. and this. |
||
Fields::Named(fields) => multiunzip( | ||
fields | ||
.named | ||
.iter() | ||
.filter(filter_not_reserved_or_padding) | ||
.enumerate() | ||
.map(|(i, f)| deserialize_field_parts(i, f.ident.as_ref().unwrap())), | ||
), | ||
Fields::Unnamed(fields) => multiunzip( | ||
fields | ||
.unnamed | ||
.iter() | ||
.enumerate() | ||
.map(|(i, _)| deserialize_field_parts(i, &syn::parse_str(&format!("val_{}", i)).unwrap_or_else(unreachable))), | ||
), | ||
Fields::Unit => todo!("this is a unit struct, which is not supported right now"), | ||
}; | ||
|
||
if field_expecting.len() > 1 { | ||
field_expecting.last_mut().unwrap().insert_str(0, "or "); | ||
} | ||
let field_expecting = field_expecting.join(", "); | ||
|
||
let visit_map = if should_have_visit_map { | ||
quote!(fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> | ||
where | ||
V: ::serde::de::MapAccess<'de>, | ||
{ | ||
#(#field_visit_map_init)* | ||
while let Some(key) = map.next_key()? { | ||
match key { | ||
#(#field_visit_map_match)* | ||
} | ||
} | ||
#(#field_visit_map_check)* | ||
Ok(#name::new(#(#field_names)*)) | ||
}) | ||
} else { | ||
quote!() | ||
}; | ||
|
||
quote! { | ||
impl<'de> ::serde::Deserialize<'de> for #name { | ||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> | ||
where | ||
D: ::serde::Deserializer<'de>, | ||
{ | ||
#[allow(non_camel_case_types)] | ||
enum Field { #(#field_names)* } | ||
impl<'de> ::serde::Deserialize<'de> for Field { | ||
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> | ||
where | ||
D: ::serde::Deserializer<'de>, | ||
{ | ||
struct FieldVisitor; | ||
|
||
impl<'de> ::serde::de::Visitor<'de> for FieldVisitor { | ||
type Value = Field; | ||
|
||
fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { | ||
formatter.write_str(#field_expecting) | ||
} | ||
|
||
fn visit_str<E>(self, value: &str) -> Result<Field, E> | ||
where | ||
E: ::serde::de::Error, | ||
{ | ||
match value { | ||
#(#field_deserialize)* | ||
_ => Err(::serde::de::Error::unknown_field(value, FIELDS)), | ||
} | ||
} | ||
} | ||
|
||
deserializer.deserialize_identifier(FieldVisitor) | ||
} | ||
} | ||
|
||
struct Visitor; | ||
|
||
impl<'de> ::serde::de::Visitor<'de> for Visitor { | ||
type Value = #name; | ||
|
||
fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { | ||
formatter.write_str(#struct_name_str) | ||
} | ||
|
||
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error> | ||
where | ||
V: ::serde::de::SeqAccess<'de>, | ||
{ | ||
#(#field_visit_seq)* | ||
Ok(Self::Value::new(#(#field_names)*)) | ||
} | ||
|
||
#visit_map | ||
} | ||
|
||
const FIELDS: &'static [&'static str] = &[#(#field_name_strings)*]; | ||
deserializer.deserialize_struct(#name_str, FIELDS, Visitor) | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These tests are nice, but we have to have one testing an arbitrary integer field ser-de 😄 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
#![cfg(feature = "serde")] | ||
|
||
use bilge::prelude::*; | ||
use serde_test::{assert_de_tokens_error, assert_tokens, Token}; | ||
|
||
#[bitsize(17)] | ||
#[derive(FromBits, PartialEq, SerializeBits, DeserializeBits, DebugBits)] | ||
struct BitsStruct { | ||
field1: u8, | ||
field2: u8, | ||
padding: u1, | ||
} | ||
|
||
#[test] | ||
fn serde_struct() { | ||
let bits = BitsStruct::from(u17::new(0b0_0000_0001_0010_0011)); | ||
|
||
assert_tokens( | ||
&bits, | ||
&[ | ||
Token::Struct { name: "BitsStruct", len: 2 }, | ||
Token::Str("field1"), | ||
Token::U8(0b0010_0011), | ||
Token::Str("field2"), | ||
Token::U8(0b0000_0001), | ||
Token::StructEnd, | ||
], | ||
); | ||
} | ||
|
||
#[test] | ||
fn serde_struct_missing_field() { | ||
assert_de_tokens_error::<BitsStruct>( | ||
&[ | ||
Token::Struct { name: "BitsStruct", len: 1 }, | ||
Token::Str("field1"), | ||
Token::U8(0b0010_0011), | ||
Token::StructEnd, | ||
], | ||
"missing field `field2`", | ||
); | ||
} | ||
|
||
#[test] | ||
fn serde_struct_extra_field() { | ||
assert_de_tokens_error::<BitsStruct>( | ||
&[ | ||
Token::Struct { name: "BitsStruct", len: 3 }, | ||
Token::Str("field1"), | ||
Token::U8(0b0010_0011), | ||
Token::Str("field2"), | ||
Token::U8(0b0000_0001), | ||
Token::Str("field3"), | ||
], | ||
"unknown field `field3`, expected `field1` or `field2`", | ||
); | ||
} | ||
|
||
#[bitsize(16)] | ||
#[derive(FromBits, PartialEq, SerializeBits, DeserializeBits, DebugBits)] | ||
struct BitsTupleStruct(u8, u8); | ||
|
||
#[test] | ||
fn serde_tuple_struct() { | ||
let bits = BitsTupleStruct::from(0b0000_0001_0010_0011); | ||
|
||
assert_tokens( | ||
&bits, | ||
&[ | ||
Token::TupleStruct { | ||
name: "BitsTupleStruct", | ||
len: 2, | ||
}, | ||
Token::U8(0b0010_0011), | ||
Token::U8(0b0000_0001), | ||
Token::TupleStructEnd, | ||
], | ||
); | ||
} | ||
|
||
#[test] | ||
fn serde_tuple_struct_map() { | ||
assert_de_tokens_error::<BitsTupleStruct>( | ||
&[ | ||
Token::TupleStruct { name: "BitsStruct", len: 3 }, | ||
Token::Str("val_0"), | ||
], | ||
r#"invalid type: string "val_0", expected u8"#, | ||
); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't like this.