Crates.io | serde_merge |
lib.rs | serde_merge |
version | 0.1.3 |
source | src |
created_at | 2021-07-03 18:05:34.494896 |
updated_at | 2021-12-30 10:25:28.703644 |
description | Simple utility to merge some serializable data types. |
homepage | https://github.com/Z4RX/serde_merge |
repository | https://github.com/Z4RX/serde_merge |
max_upload_size | |
id | 418278 |
size | 21,877 |
Simple utility to merge some serializable data types based on serde.
use serde_merge::mmerge;
use std::collections::HashMap;
fn main() {
let mut map1: HashMap<&str, &str> = HashMap::new();
map1.insert("key1", "value1");
map1.insert("key2", "value2");
map1.insert("key3", "value3");
let mut map2: HashMap<&str, &str> = HashMap::new();
map2.insert("key4", "value4");
map2.insert("key5", "value5");
map2.insert("key6", "value6");
let result = mmerge(map1, map2).unwrap();
println!("{:#?}", result);
// --Output--
// {
// "key1": String(
// "value1",
// ),
// "key2": String(
// "value2",
// ),
// "key3": String(
// "value3",
// ),
// "key4": String(
// "value4",
// ),
// "key5": String(
// "value5",
// ),
// "key6": String(
// "value6",
// ),
// }
}
use serde::{Deserialize, Serialize};
use serde_merge::tmerge;
#[derive(Serialize, Deserialize)]
struct Foo {
pub field1: String,
pub field2: i32,
}
#[derive(Serialize, Deserialize)]
struct Bar {
pub field3: Vec<String>,
pub field4: u32,
}
#[derive(Debug, Serialize, Deserialize)]
struct Result {
pub field1: String,
pub field2: i32,
pub field3: Vec<String>,
pub field4: u32,
}
fn main() {
let foo = Foo {
field1: "field1".to_string(),
field2: 15,
};
let bar = Bar {
field3: Vec::from([
"elem1".to_string(),
"elem2".to_string(),
"elem3".to_string(),
]),
field4: 5,
};
// unwrap is not recommended, handle Result in your app
let result: Result = tmerge(foo, bar).unwrap();
println!("{:#?}", result);
// --Output--
// Result {
// field1: "field1",
// field2: 15,
// field3: [
// "elem1",
// "elem2",
// "elem3",
// ],
// field4: 5,
// }
}
Merging structs require derive
feature for serde
.
use serde::{Deserialize, Serialize};
use serde_merge::omerge;
#[derive(Serialize, Deserialize, PartialEq)]
struct HasOptional {
field1: i32,
field2: Option<bool>,
field3: Option<String>,
}
pub fn main() {
let s1 = HasOptional {
field1: 1,
field2: None,
field3: Some("3".to_string()),
};
let s2 = HasOptional {
field1: 2,
field2: Some(true),
field3: None,
};
let result: HasOptional = omerge(s1, s2).unwrap();
let target = HasOptional {
field1: 2,
field2: Some(true),
field3: Some("3".to_string()),
};
assert_eq!(result, target); // true
}