Skip to content

Commit

Permalink
Add example for toml and duration
Browse files Browse the repository at this point in the history
  • Loading branch information
yanganto committed Oct 2, 2024
1 parent 25231c2 commit 8c9ac96
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ jobs:
nix develop -c cargo run --no-default-features --example json
nix develop -c cargo run --no-default-features --example rename-patch-struct
nix develop -c cargo run --no-default-features --example patch-attr
nix develop -c cargo run --no-default-features --example time
nix develop -c cargo test --no-default-features
- name: Test with std features
Expand Down
2 changes: 2 additions & 0 deletions struct-patch/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ struct-patch-derive = { version = "=0.8.5", path = "../struct-patch-derive" }
serde_json = "1.0"
serde = { version = "1", features = ["derive"] }
serde_with = "3.9.0"
toml = "0.8.19"
humantime-serde = "1.1.1"

[features]
default = ["status", "op"]
Expand Down
34 changes: 34 additions & 0 deletions struct-patch/examples/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use serde::{Deserialize};
use std::time::Duration;
use struct_patch::Patch;

#[derive(Deserialize, Clone, Debug, Patch)]
#[patch(name = "FileConfig", attribute(derive(Deserialize, Debug)))]
struct Config {
#[serde(with = "humantime_serde")]
#[patch(attribute(serde(with = "humantime_serde")))]
time: Duration,
}

fn main() {
let config = Config {
time: Duration::from_millis(500),
};

let patch: FileConfig = toml::from_str("time = \"200ms\"").unwrap();

let mut patched = config.clone();
patched.apply(patch);
assert_eq!(patched.time, Duration::from_millis(200));

// NOTE
// Following code does not work, because `humantime_serde` does not allow `Option<>` field
// anymore.
// https://github.com/jean-airoldie/humantime-serde/issues/13
//
// let empty_patch: FileConfig = toml::from_str("").unwrap();

// let mut patched = config.clone();
// patched.apply(empty_patch);
// assert_eq!(patched.time, Duration::from_millis(500));
}

0 comments on commit 8c9ac96

Please sign in to comment.