Skip to main content

full/
full.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
4struct Profile {
5    bio: String,
6    avatar_url: Option<String>,
7}
8
9#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
10struct User {
11    id: u32,
12    username: String,
13    age: u8,
14    active: bool,
15    profile: Option<Profile>,
16}
17
18fn main() -> Result<(), Box<dyn std::error::Error>> {
19    let old = User {
20        id: 1001,
21        username: "alice".to_string(),
22        age: 30,
23        active: true,
24        profile: Some(Profile {
25            bio: "Software engineer".to_string(),
26            avatar_url: Some("https://example.com/alice-old.jpg".to_string()),
27        }),
28    };
29
30    let new = User {
31        id: 1001,
32        username: "alice".to_string(),
33        age: 31,
34        active: false,
35        profile: Some(Profile {
36            bio: "Senior software engineer".to_string(),
37            avatar_url: None,
38        }),
39    };
40
41    // Basic diff – only changed fields
42    let basic_patch = serde_json::to_string(&serde_patch::diff(&old, &new)?)?;
43    println!("Basic patch (no forced fields):\n{}", basic_patch);
44
45    // Diff with forced field – includes "id" even though unchanged
46    let forced_patch = serde_json::to_string(&serde_patch::diff_including(&old, &new, &["id"])?)?;
47    println!("\nPatch with forced \"id\":\n{}", forced_patch);
48
49    // Apply immutably
50    let updated = serde_patch::apply(old.clone(), &basic_patch)?;
51    println!("\nImmutable apply result:\n{:#?}", updated);
52
53    // Apply mutably
54    let mut current = old;
55    serde_patch::apply_mut(&mut current, &forced_patch)?;
56    println!("\nMutable apply result:\n{:#?}", current);
57
58    assert_eq!(updated, new);
59    assert_eq!(current, new);
60
61    Ok(())
62}