serde-diff icon indicating copy to clipboard operation
serde-diff copied to clipboard

Apply Option difference to `None` target doesn't work as expected

Open User-TGK opened this issue 4 years ago • 3 comments

Example to reproduce the issue

use serde::{Deserialize, Serialize};
use serde_diff::{Apply, Diff, SerdeDiff};

#[derive(SerdeDiff, Serialize, Deserialize, PartialEq, Debug, Clone)]
struct TestStruct {
    a: Option<i32>,
}

fn main() {
    let old = TestStruct { a: Some(5) };
    let new = TestStruct { a: Some(10) };
    let mut target = TestStruct { a: None };
    let expected = new.clone();

    let diff = Diff::serializable(&old, &new);
    let json_diff = serde_json::to_string(&diff).unwrap();
    let mut deserializer = serde_json::Deserializer::from_str(&json_diff);

    Apply::apply(&mut deserializer, &mut target).unwrap();

    assert_eq!(target, expected);
}

Expected result

For target to equal TestStruct { a: Some(10) }

Actual result

Target equals TestStruct { a: None }

User-TGK avatar Apr 12 '21 10:04 User-TGK

@kabergstrom Any idea why that could be? If both are Some, their contents are compared here: https://github.com/amethyst/serde-diff/blob/e461da41c9339af3ecadf9f4aa61ae91c1f79e97/src/implementation.rs#L345

Boscop avatar Apr 15 '21 17:04 Boscop

@User-TGK Actually, I think you're applying it wrongly (@kabergstrom Correct me if I'm wrong): SerdeDiff assumes that the target you're applying the diff to is equal to the old value that was used to compute the diff. (In other words, the computed diff is only valid to be applied to an object that is equal to the old value it was computed from.) So you should assert that the diff applied to old equals new.

I ran into a similar issue here: https://github.com/amethyst/serde-diff/issues/16#issuecomment-673628784 In my use case I'm sending diffs over websockets. I solved that issue by resetting the client's copy of the state to Default::default() upon reconnect (because while the client was disconnected, its instance of the state went out of sync with the server's instance, which would make the next diff invalid to be applied to the client's instance), and then the server sends diff(Default::default(), current) to the client right after reconnect, before any other msgs. Let me know if you find a better workaround :)

Boscop avatar Apr 15 '21 18:04 Boscop

Thanks for the info @Boscop. The workaround I currently use is replacing the following line with the snippet below.

https://github.com/amethyst/serde-diff/blob/e461da41c9339af3ecadf9f4aa61ae91c1f79e97/src/implementation.rs#L383

    if let Value(v) = ctx
        .read_next_command(seq)?
        .expect("Expected value")
    {
        changed = true;
        *self = Some(v);
    }

I didn't look into the implementation details of the library so I am not sure whether this will cause issues, but it does the trick for now.

User-TGK avatar Apr 16 '21 08:04 User-TGK