Skip to content

Commit

Permalink
add option string trim
Browse files Browse the repository at this point in the history
  • Loading branch information
baoyachi committed Jun 17, 2022
1 parent 42408ce commit 0c51e72
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "serde_trim"
version = "0.2.0"
version = "0.3.0"
authors = ["baoyachi <[email protected]>"]
edition = "2021"
description = "serde deserialize_with String trim"
Expand Down
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,22 @@
## how to use
```rust
fn main() {
#[derive(Debug, Deserialize)]
#[derive(Deserialize)]
struct Foo {
#[serde(deserialize_with = "string_trim")]
name: String,
}
let json = r#"{"name":" "}"#;
let foo = serde_json::from_str::<Foo>(json).unwrap();
assert_eq!(foo.name, "");

#[derive(Deserialize)]
struct OptionFoo {
#[serde(deserialize_with = "option_string_trim")]
name: Option<String>,
}
let json = r#"{"name":" "}"#;
let foo = serde_json::from_str::<OptionFoo>(json).unwrap();
assert_eq!(foo.name, None);
}
```
27 changes: 26 additions & 1 deletion lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,22 @@ where
Ok(de_string)
}

pub fn option_string_trim<'de, D>(d: D) -> Result<Option<String>, D::Error>
where
D: de::Deserializer<'de>,
{
let mut de_string: Option<String> = Option::deserialize(d)?;
if let Some(ref mut de_string) = de_string {
if de_string.trim_in_place().is_empty() {
return Ok(None);
}
}
Ok(de_string)
}

#[test]
fn test_string_trim() {
#[derive(Debug, Deserialize)]
#[derive(Deserialize)]
struct Foo {
#[serde(deserialize_with = "string_trim")]
name: String,
Expand All @@ -21,3 +34,15 @@ fn test_string_trim() {
let foo = serde_json::from_str::<Foo>(json).unwrap();
assert_eq!(foo.name, "");
}

#[test]
fn test_option_string_trim() {
#[derive(Deserialize)]
struct OptionFoo {
#[serde(deserialize_with = "option_string_trim")]
name: Option<String>,
}
let json = r#"{"name":" "}"#;
let foo = serde_json::from_str::<OptionFoo>(json).unwrap();
assert_eq!(foo.name, None);
}

0 comments on commit 0c51e72

Please sign in to comment.