Skip to content
Open
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
72 changes: 72 additions & 0 deletions postcard-derive/src/all_fields_with.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::*;
use syn::punctuated::*;
use syn::*;

pub fn all_fields_with(
attr: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let gen = match modify_ast_to_add_with_attr(attr.into(), ast) {
Ok(g) => g,
Err(e) => return e.to_compile_error().into(),
};
gen.into_token_stream().into()
}

fn modify_ast_to_add_with_attr(with: TokenStream, ast: DeriveInput) -> Result<impl ToTokens> {
let new_data: Data = match ast.data {
syn::Data::Struct(DataStruct {
struct_token,
fields,
semi_token,
}) => match fields {
fields => modify_fields_to_add_with_attr(with, struct_token, semi_token, fields)?,
},
data => data,
};
Ok(DeriveInput {
attrs: ast.attrs,
vis: ast.vis,
ident: ast.ident,
generics: ast.generics,
data: new_data,
})
}

pub fn modify_fields_to_add_with_attr(
with: TokenStream,
struct_token: syn::token::Struct,
semi_token: Option<syn::token::Semi>,
fields: Fields,
) -> Result<Data> {
let mut fields = fields;
let attr = create_field_attribute(with);
fields.iter_mut().for_each(|f| f.attrs.push(attr.clone()));
Ok(Data::Struct(DataStruct {
struct_token,
fields: fields,
semi_token,
}))
}

fn create_field_attribute(with: TokenStream) -> Attribute {
let stream = quote!((with = #with));
let mut segments: Punctuated<PathSegment, Token![::]> = Punctuated::new();
segments.push(PathSegment {
ident: Ident::new("serde", Span::call_site()),
arguments: PathArguments::None,
});
Attribute {
pound_token: syn::token::Pound::default(),
style: syn::AttrStyle::Outer,
bracket_token: syn::token::Bracket::default(),
path: Path {
leading_colon: None,
segments,
},
tokens: stream,
}
}
9 changes: 9 additions & 0 deletions postcard-derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod all_fields_with;
mod max_size;
mod schema;

Expand All @@ -12,3 +13,11 @@ pub fn derive_max_size(item: proc_macro::TokenStream) -> proc_macro::TokenStream
pub fn derive_schema(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
schema::do_derive_schema(item)
}

#[proc_macro_attribute]
pub fn all_fields_with(
attr: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
all_fields_with::all_fields_with(attr, input)
}
102 changes: 102 additions & 0 deletions src/fixint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,28 @@ pub mod be {
}

#[doc(hidden)]
#[derive(Debug, Eq, PartialEq)]
pub struct LE<T>(T);

#[doc(hidden)]
#[derive(Debug, Eq, PartialEq)]
pub struct BE<T>(T);

macro_rules! impl_fixint {
($( $int:ty ),*) => {
$(
impl From<LE<$int>> for $int {
fn from(val: LE<$int>) -> $int {
val.0
}
}

impl From<$int> for LE<$int> {
fn from(val: $int) -> LE<$int> {
LE(val)
}
}

impl Serialize for LE<$int> {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
Expand All @@ -122,6 +136,18 @@ macro_rules! impl_fixint {
}
}

impl From<BE<$int>> for $int {
fn from(val: BE<$int>) -> $int {
val.0
}
}

impl From<$int> for BE<$int> {
fn from(val: $int) -> BE<$int> {
BE(val)
}
}

impl Serialize for BE<$int> {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
Expand Down Expand Up @@ -186,4 +212,80 @@ mod tests {
let deserialized: DefinitelyBE = crate::from_bytes(serialized).unwrap();
assert_eq!(deserialized, input);
}

#[test]
fn test_little_endian_wrapper() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct DefinitelyLE {
x: crate::fixint::LE<u16>,
}

let input = DefinitelyLE { x: 0xABCD.into() };
let mut buf = [0; 32];
let serialized = crate::to_slice(&input, &mut buf).unwrap();
assert_eq!(serialized, &[0xCD, 0xAB]);

let deserialized: DefinitelyLE = crate::from_bytes(serialized).unwrap();
assert_eq!(deserialized, input);
}

#[test]
fn test_big_endian_wrapper() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct DefinitelyBE {
x: crate::fixint::BE<u16>,
}

let input = DefinitelyBE { x: 0xABCD.into() };
let mut buf = [0; 32];
let serialized = crate::to_slice(&input, &mut buf).unwrap();
assert_eq!(serialized, &[0xAB, 0xCD]);

let deserialized: DefinitelyBE = crate::from_bytes(serialized).unwrap();
assert_eq!(deserialized, input);
}

#[cfg(feature = "experimental-derive")]
#[test]
fn test_all_fields_with_be() {
#[postcard_derive::all_fields_with("crate::fixint::be")]
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct DefinitelyBE {
x: u16,
y: u32,
}

let input = DefinitelyBE {
x: 0xABCD,
y: 0xEF123456,
};
let mut buf = [0; 32];
let serialized = crate::to_slice(&input, &mut buf).unwrap();
assert_eq!(serialized, &[0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56]);

let deserialized: DefinitelyBE = crate::from_bytes(serialized).unwrap();
assert_eq!(deserialized, input);
}

#[cfg(feature = "experimental-derive")]
#[test]
fn test_all_fields_with_le() {
#[postcard_derive::all_fields_with("crate::fixint::le")]
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct DefinitelyLE {
x: u16,
y: u32,
}

let input = DefinitelyLE {
x: 0xABCD,
y: 0xEF123456,
};
let mut buf = [0; 32];
let serialized = crate::to_slice(&input, &mut buf).unwrap();
assert_eq!(serialized, &[0xCD, 0xAB, 0x56, 0x34, 0x12, 0xEF]);

let deserialized: DefinitelyLE = crate::from_bytes(serialized).unwrap();
assert_eq!(deserialized, input);
}
}