Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add newline separators #777

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions serde_with/src/formats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,23 @@ impl Separator for ColonSeparator {
":"
}
}

/// Predefined separator using a single linefeed.
pub struct UnixLineSeparator;

impl Separator for UnixLineSeparator {
#[inline]
fn separator() -> &'static str {
"\n"
}
}

/// Predefined separator using a DOS/Windows line ending.
pub struct DosLineSeparator;

impl Separator for DosLineSeparator {
#[inline]
fn separator() -> &'static str {
"\r\n"
}
}
28 changes: 23 additions & 5 deletions serde_with/tests/serde_as/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ fn test_bytes_or_string() {
#[test]
fn string_with_separator() {
use serde_with::{
formats::{CommaSeparator, SpaceSeparator},
formats::{CommaSeparator, DosLineSeparator, SpaceSeparator, UnixLineSeparator},
StringWithSeparator,
};

Expand All @@ -529,26 +529,44 @@ fn string_with_separator() {
#[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
tags: Vec<String>,
#[serde_as(as = "StringWithSeparator::<CommaSeparator, String>")]
// more_tags: Vec<String>,
more_tags: BTreeSet<String>,
#[serde_as(as = "StringWithSeparator::<UnixLineSeparator, String>")]
lf_tags: BTreeSet<String>,
#[serde_as(as = "StringWithSeparator::<DosLineSeparator, String>")]
crlf_tags: BTreeSet<String>,
}

let v: A = serde_json::from_str(
r##"{
"tags": "#hello #world",
"more_tags": "foo,bar,bar"
"more_tags": "foo,bar,bar",
"lf_tags": "foo\nbar\nbar",
"crlf_tags": "foo\r\nbar\r\nbar"
}"##,
)
.unwrap();
assert_eq!(vec!["#hello", "#world"], v.tags);
assert_eq!(2, v.more_tags.len());
assert_eq!(
BTreeSet::from(["foo".to_string(), "bar".to_string()]),
v.more_tags
);
assert_eq!(
BTreeSet::from(["foo".to_string(), "bar".to_string()]),
v.lf_tags
);
assert_eq!(
BTreeSet::from(["foo".to_string(), "bar".to_string()]),
v.crlf_tags
);

let x = A {
tags: vec!["1".to_string(), "2".to_string(), "3".to_string()],
more_tags: BTreeSet::default(),
lf_tags: BTreeSet::default(),
crlf_tags: BTreeSet::default(),
};
assert_eq!(
r#"{"tags":"1 2 3","more_tags":""}"#,
r#"{"tags":"1 2 3","more_tags":"","lf_tags":"","crlf_tags":""}"#,
serde_json::to_string(&x).unwrap()
);
}
Expand Down