Skip to content

Commit

Permalink
Merge pull request #2 from leroyguillaume/main
Browse files Browse the repository at this point in the history
Support BTreeSet
  • Loading branch information
baoyachi authored Jul 23, 2023
2 parents 5c7cd1d + 6e12d7d commit 6b1b027
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
## Support trim
* `String`
* `Vec<String>`
* `BTreeSet<String>`
* `Option<String>`


Expand Down Expand Up @@ -55,5 +56,21 @@ fn main() {
let json = r#"{"name":[" ","foo","b ar","hello "," rust"]}"#;
let foo = serde_json::from_str::<VecFoo>(json).unwrap();
assert_eq!(foo.name, vec!["", "foo", "b ar", "hello", "rust"]);

#[derive(Deserialize)]
struct BTreeSetFoo {
#[serde(deserialize_with = "btreeset_string_trim")]
name: BTreeSet<String>,
}
let json = r#"{"name":[" ","foo","b ar","hello "," rust"]}"#;
let foo = serde_json::from_str::<BTreeSetFoo>(json).unwrap();
let expected: BTreeSet<String> = BTreeSet::from_iter([
"".into(),
"foo".into(),
"b ar".into(),
"hello".into(),
"rust".into(),
]);
assert_eq!(foo.name, expected);
}
```
32 changes: 32 additions & 0 deletions lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::BTreeSet;

use serde::{de, Deserialize};
pub use trim_in_place::*;

Expand Down Expand Up @@ -34,6 +36,17 @@ where
Ok(de_string)
}

pub fn btreeset_string_trim<'de, D>(d: D) -> Result<BTreeSet<String>, D::Error>
where
D: de::Deserializer<'de>,
{
let de_string: BTreeSet<String> = BTreeSet::<String>::deserialize(d)?
.into_iter()
.map(|mut x| x.trim_in_place().to_string())
.collect();
Ok(de_string)
}

#[test]
fn test_vec_string_trim() {
#[derive(Deserialize)]
Expand Down Expand Up @@ -80,3 +93,22 @@ fn test_option_string_trim() {
assert_eq!(foo.name, None);
assert_eq!(foo.addr, "ABC");
}

#[test]
fn test_btreeset_string_trim() {
#[derive(Deserialize)]
struct BTreeSetFoo {
#[serde(deserialize_with = "btreeset_string_trim")]
name: BTreeSet<String>,
}
let json = r#"{"name":[" ","foo","b ar","hello "," rust"]}"#;
let foo = serde_json::from_str::<BTreeSetFoo>(json).unwrap();
let expected: BTreeSet<String> = BTreeSet::from_iter([
"".into(),
"foo".into(),
"b ar".into(),
"hello".into(),
"rust".into(),
]);
assert_eq!(foo.name, expected);
}

0 comments on commit 6b1b027

Please sign in to comment.