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

Add set support #34

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ serde_json
- [x] BTreeMap (thanks @milkey-mouse)
- [x] Fixed-size arrays (thanks @Boscop)
- [x] Tuples (thanks @Boscop)
- [x] HashSet (thanks @Diggsey)
- [x] BTreeSet (thanks @Diggsey)

# Simple example

Expand Down
10 changes: 10 additions & 0 deletions examples/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,20 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.map
.insert("hi".to_string(), vec!["planet".to_string()]);

let mut hi_planet_hello_world = TestStruct::default();
hi_planet_hello_world
.map
.insert("hi".to_string(), vec!["planet".to_string()]);
hi_planet_hello_world
.map
.insert("hello".to_string(), vec!["world".to_string()]);

let add_hello = serde_json::to_string(&Diff::serializable(&empty, &hello_world))?;
let hello_to_hi = serde_json::to_string(&Diff::serializable(&hello_world, &hi_world))?;
let add_planet = serde_json::to_string(&Diff::serializable(&hi_world, &hi_world_and_planet))?;
let del_world = serde_json::to_string(&Diff::serializable(&hi_world_and_planet, &hi_planet))?;
let no_change = serde_json::to_string(&Diff::serializable(&hi_planet, &hi_planet))?;
let add_world = serde_json::to_string(&Diff::serializable(&hi_planet, &hi_planet_hello_world))?;

let mut built = TestStruct::default();
for (diff, after) in &[
Expand All @@ -47,6 +56,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
(add_planet, hi_world_and_planet),
(del_world, hi_planet.clone()),
(no_change, hi_planet),
(add_world, hi_planet_hello_world),
] {
println!("{}", diff);

Expand Down
51 changes: 51 additions & 0 deletions examples/set.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use serde::{Deserialize, Serialize};
use serde_diff::{Apply, Diff, SerdeDiff};
use std::collections::HashSet;

#[derive(SerdeDiff, Serialize, Deserialize, Debug, Default, PartialEq, Clone)]
struct TestStruct {
test: bool,
//#[serde_diff(opaque)]
set: HashSet<String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut empty = TestStruct::default();
empty.test = true;

let mut a = TestStruct::default();
a.set.insert("a".to_string());

let mut ab = TestStruct::default();
ab.set.insert("a".to_string());
ab.set.insert("b".to_string());

let mut b = TestStruct::default();
b.set.insert("b".to_string());

let mut c = TestStruct::default();
c.set.insert("c".to_string());

let add_a = serde_json::to_string(&Diff::serializable(&empty, &a))?;
let add_b = serde_json::to_string(&Diff::serializable(&a, &ab))?;
let del_a = serde_json::to_string(&Diff::serializable(&ab, &b))?;
let rep_b_c = serde_json::to_string(&Diff::serializable(&b, &c))?;
let no_change = serde_json::to_string(&Diff::serializable(&c, &c))?;

let mut built = TestStruct::default();
for (diff, after) in &[
(add_a, a),
(add_b, ab),
(del_a, b),
(rep_b_c, c.clone()),
(no_change, c),
] {
println!("{}", diff);

let mut deserializer = serde_json::Deserializer::from_str(&diff);
Apply::apply(&mut deserializer, &mut built)?;

assert_eq!(after, &built);
}
Ok(())
}
25 changes: 18 additions & 7 deletions serde-diff-derive/src/serde_diff/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ fn generate_fields_diff(
let right = format_ident!("r{}", field_idx);

let push = if let Some(_) = ident {
quote!{ctx.push_field(#ident_as_str);}
quote!{ctx.push_field(#field_idx, #ident_as_str);}
} else {
quote!{ctx.push_field_index(#field_idx);}
};
Expand Down Expand Up @@ -170,7 +170,7 @@ fn ok_fields(fields : &syn::Fields) -> Result<Vec<ParsedField>, proc_macro::Toke
}
}

fn generate_arms(name: &syn::Ident, variant: Option<&syn::Ident>, fields: &syn::Fields, matching: bool)
fn generate_arms(name: &syn::Ident, variant: Option<(u16, &syn::Ident)>, fields: &syn::Fields, matching: bool)
-> Result<(Vec<proc_macro2::TokenStream>, Vec<proc_macro2::TokenStream>),
proc_macro2::TokenStream>
{
Expand All @@ -182,14 +182,15 @@ fn generate_arms(name: &syn::Ident, variant: Option<&syn::Ident>, fields: &syn::
matching,
);
let (left, right) = enum_fields(&fields, false);
let variant_specifier = if let Some(id) = variant {
let variant_specifier = if let Some((_, id)) = variant {
quote!{ :: #id}
} else {
quote!{}
};

let variant_as_str = variant.map(|i| i.to_string());
let push_variant = variant.map(|_| quote!{ctx.push_variant(#variant_as_str);});
let variant_idx = variant.map(|(i, _)| i);
let variant_as_str = variant.map(|(_, i)| i.to_string());
let push_variant = variant.map(|_| quote!{ctx.push_variant(#variant_idx, #variant_as_str);});
let pop_variant = variant.map(|_| quote!{ctx.pop_path_element()?;});

let left = if matching {
Expand Down Expand Up @@ -259,6 +260,16 @@ fn generate_arms(name: &syn::Ident, variant: Option<&syn::Ident>, fields: &syn::
}

if let Some(_) = variant {
apply_match_arms.push(quote!{
( &mut #name #variant_specifier #left, Some(serde_diff::DiffPathElementValue::EnumVariantIndex(#variant_idx))) => {
while let Some(element) = ctx.next_path_element(seq)? {
match element {
#(#apply_fn_field_handlers)*
_ => ctx.skip_value(seq)?
}
}
}
});
apply_match_arms.push(quote!{
( &mut #name #variant_specifier #left, Some(serde_diff::DiffPathElementValue::EnumVariant(variant))) if variant == #variant_as_str => {
while let Some(element) = ctx.next_path_element(seq)? {
Expand Down Expand Up @@ -299,8 +310,8 @@ fn generate(
let has_variants = match &input.data {
Data::Enum(e) => {
for matching in &[true, false] {
for v in &e.variants {
let (diff, apply) = generate_arms(&struct_args.ident, Some(&v.ident), &v.fields, *matching)?;
for (i, v) in e.variants.iter().enumerate() {
let (diff, apply) = generate_arms(&struct_args.ident, Some((i as u16, &v.ident)), &v.fields, *matching)?;
diff_match_arms.extend(diff);
apply_match_arms.extend(apply);
}
Expand Down
36 changes: 27 additions & 9 deletions src/difference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,21 +58,38 @@ impl<'a, S: SerializeSeq> DiffContext<'a, S> {
/// Called when we visit a field. If the structure is recursive (i.e. struct within struct,
/// elements within an array) this may be called more than once before a corresponding pop_path_element
/// is called. See `pop_path_element`
pub fn push_field(&mut self, field_name: &'static str) {
self.element_stack
.as_mut()
.unwrap()
.push(ElementStackEntry::PathElement(DiffPathElementValue::Field(
Cow::Borrowed(field_name),
)));
pub fn push_field(&mut self, field_idx: u16, field_name: &'static str) {
if matches!(self.field_path_mode, FieldPathMode::Index) {
self.push_field_index(field_idx);
} else {
self.element_stack
.as_mut()
.unwrap()
.push(ElementStackEntry::PathElement(DiffPathElementValue::Field(
Cow::Borrowed(field_name),
)));
}
}

pub fn push_variant(&mut self, variant_idx: u16, variant_name: &'static str) {
if matches!(self.field_path_mode, FieldPathMode::Index) {
self.push_variant_index(variant_idx);
} else {
self.element_stack
.as_mut()
.unwrap()
.push(ElementStackEntry::PathElement(
DiffPathElementValue::EnumVariant(Cow::Borrowed(variant_name)),
));
}
}

pub fn push_variant(&mut self, variant_name: &'static str) {
pub fn push_variant_index(&mut self, variant_idx: u16) {
self.element_stack
.as_mut()
.unwrap()
.push(ElementStackEntry::PathElement(
DiffPathElementValue::EnumVariant(Cow::Borrowed(variant_name)),
DiffPathElementValue::EnumVariantIndex(variant_idx),
));
}

Expand Down Expand Up @@ -601,6 +618,7 @@ pub enum DiffPathElementValue<'a> {
Field(Cow<'a, str>),
FieldIndex(u16),
EnumVariant(Cow<'a, str>),
EnumVariantIndex(u16),
FullEnumVariant,
CollectionIndex(usize),
AddToCollection,
Expand Down
82 changes: 77 additions & 5 deletions src/implementation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
use serde::{de, ser::SerializeSeq, Deserialize, Serialize};

use std::{
collections::{BTreeMap, HashMap},
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
hash::Hash,
};

Expand Down Expand Up @@ -96,7 +96,7 @@ macro_rules! tuple_impls {
) -> Result<bool, S::Error> {
let mut changed = false;
$(
ctx.push_field(stringify!($n));
ctx.push_field_index($n);
changed |= <$name as $crate::SerdeDiff>::diff(&self.$n, ctx, &other.$n)?;
ctx.pop_path_element()?;
)+
Expand All @@ -112,10 +112,10 @@ macro_rules! tuple_impls {
A: serde::de::SeqAccess<'de>,
{
let mut changed = false;
while let Some($crate::difference::DiffPathElementValue::Field(element)) = ctx.next_path_element(seq)? {
match element.as_ref() {
while let Some($crate::difference::DiffPathElementValue::FieldIndex(element)) = ctx.next_path_element(seq)? {
match element {
$(
stringify!($n) => changed |= <$name as $crate::SerdeDiff>::apply(&mut self.$n, seq, ctx)?,
$n => changed |= <$name as $crate::SerdeDiff>::apply(&mut self.$n, seq, ctx)?,
)+
_ => ctx.skip_value(seq)?,
}
Expand Down Expand Up @@ -237,6 +237,78 @@ macro_rules! map_serde_diff {
map_serde_diff!(HashMap<K, V>, Hash, Eq);
map_serde_diff!(BTreeMap<K, V>, Ord);

/// Implement SerdeDiff on a "set-like" type such as HashSet.
macro_rules! set_serde_diff {
($t:ty, $($extra_traits:path),*) => {
impl<K> SerdeDiff for $t
where
K: SerdeDiff + Serialize + for<'a> Deserialize<'a> $(+ $extra_traits)*, // + Hash + Eq,
{
fn diff<'a, S: SerializeSeq>(
&self,
ctx: &mut $crate::difference::DiffContext<'a, S>,
other: &Self,
) -> Result<bool, S::Error> {
use $crate::difference::DiffCommandRef;

let mut changed = false;

// TODO: detect renames
for key in self.iter() {
if !other.contains(key) {
ctx.save_command(&DiffCommandRef::RemoveKey(key), true, true)?;
changed = true;
}
}

for key in other.iter() {
if !self.contains(key) {
ctx.save_command(&DiffCommandRef::AddKey(key), true, true)?;
changed = true;
}
}

if changed {
ctx.save_command::<()>(&DiffCommandRef::Exit, true, false)?;
}
Ok(changed)
}

fn apply<'de, A>(
&mut self,
seq: &mut A,
ctx: &mut ApplyContext,
) -> Result<bool, <A as de::SeqAccess<'de>>::Error>
where
A: de::SeqAccess<'de>,
{
let mut changed = false;
while let Some(cmd) = ctx.read_next_command::<A, K>(seq)? {
use $crate::difference::DiffCommandValue::*;
use $crate::difference::DiffPathElementValue::*;
match cmd {
// we should not be getting fields when reading collection commands
Enter(Field(_)) | EnterKey(_) => {
ctx.skip_value(seq)?;
break;
}
AddKey(key) => {
self.insert(key);
changed = true;
}
RemoveKey(key) => changed |= self.remove(&key),
_ => break,
}
}
Ok(changed)
}
}
};
}

set_serde_diff!(HashSet<K>, Hash, Eq);
set_serde_diff!(BTreeSet<K>, Ord);

/// Implements SerdeDiff on a type given that it impls Serialize + Deserialize + PartialEq.
/// This makes the type a "terminal" type in the SerdeDiff hierarchy, meaning deeper inspection
/// will not be possible. Use the SerdeDiff derive macro for recursive field inspection.
Expand Down