Skip to content

Commit

Permalink
feat: vec_string
Browse files Browse the repository at this point in the history
  • Loading branch information
robjtede committed May 25, 2024
1 parent c7eeff7 commit 7fcce3b
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Add `vec_string()` function.

## 0.1.0

- Add `string()` function.
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ extern crate alloc;

mod string;
mod string_non_empty;
mod vec_string;

pub use crate::{
string::string,
string_non_empty::{option_string_non_empty, string_non_empty},
vec_string::vec_string,
};
2 changes: 1 addition & 1 deletion src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ mod tests {
}

serde_json::from_str::<Foo>(r#"{ "foo": 1 }"#).unwrap_err();
serde_json::from_str::<Foo>(r#"{ "foo": bool }"#).unwrap_err();
serde_json::from_str::<Foo>(r#"{ "foo": true }"#).unwrap_err();

assert_eq!(
Foo::new(""),
Expand Down
74 changes: 74 additions & 0 deletions src/vec_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use alloc::{borrow::ToOwned as _, string::String, vec::Vec};

use serde::{Deserialize as _, Deserializer};

/// Trims list of strings during deserialization.
pub fn vec_string<'a, D: Deserializer<'a>>(de: D) -> Result<Vec<String>, D::Error> {
let mut list = Vec::<String>::deserialize(de)?;

for item in &mut list {
*item = item.trim().to_owned();
}

Ok(list)
}

#[cfg(test)]
mod tests {
use serde::Deserialize;

use super::*;

#[test]
fn vec_string() {
#[derive(Debug, Deserialize, PartialEq, Eq)]
struct Foo {
#[serde(deserialize_with = "super::vec_string")]
foo: Vec<String>,
}

impl Foo {
fn new(foo: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
foo: foo.into_iter().map(Into::into).collect(),
}
}
}

serde_json::from_str::<Foo>(r#"{ "foo": 1 }"#).unwrap_err();
serde_json::from_str::<Foo>(r#"{ "foo": "" }"#).unwrap_err();

assert_eq!(
Foo::new([""; 0]),
serde_json::from_str(r#"{ "foo": [] }"#).unwrap(),
);
assert_eq!(
Foo::new([""]),
serde_json::from_str(r#"{ "foo": [""] }"#).unwrap(),
);
assert_eq!(
Foo::new([""]),
serde_json::from_str(r#"{ "foo": [" "] }"#).unwrap(),
);
assert_eq!(
Foo::new(["bar"]),
serde_json::from_str(r#"{ "foo": ["bar"] }"#).unwrap(),
);
assert_eq!(
Foo::new(["bar"]),
serde_json::from_str(r#"{ "foo": [" bar"] }"#).unwrap(),
);
assert_eq!(
Foo::new(["bar"]),
serde_json::from_str(r#"{ "foo": [" bar"] }"#).unwrap(),
);
assert_eq!(
Foo::new(["bar"]),
serde_json::from_str(r#"{ "foo": ["bar "] }"#).unwrap(),
);
assert_eq!(
Foo::new(["bar"]),
serde_json::from_str(r#"{ "foo": [" bar "] }"#).unwrap(),
);
}
}

0 comments on commit 7fcce3b

Please sign in to comment.