Skip to content

Commit aede9d5

Browse files
authored
Add newline separators (#777)
2 parents 2a28e46 + b1ee949 commit aede9d5

File tree

2 files changed

+43
-5
lines changed

2 files changed

+43
-5
lines changed

serde_with/src/formats.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,23 @@ impl Separator for ColonSeparator {
138138
":"
139139
}
140140
}
141+
142+
/// Predefined separator using a single linefeed.
143+
pub struct UnixLineSeparator;
144+
145+
impl Separator for UnixLineSeparator {
146+
#[inline]
147+
fn separator() -> &'static str {
148+
"\n"
149+
}
150+
}
151+
152+
/// Predefined separator using a DOS/Windows line ending.
153+
pub struct DosLineSeparator;
154+
155+
impl Separator for DosLineSeparator {
156+
#[inline]
157+
fn separator() -> &'static str {
158+
"\r\n"
159+
}
160+
}

serde_with/tests/serde_as/lib.rs

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ fn test_bytes_or_string() {
519519
#[test]
520520
fn string_with_separator() {
521521
use serde_with::{
522-
formats::{CommaSeparator, SpaceSeparator},
522+
formats::{CommaSeparator, DosLineSeparator, SpaceSeparator, UnixLineSeparator},
523523
StringWithSeparator,
524524
};
525525

@@ -529,26 +529,44 @@ fn string_with_separator() {
529529
#[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
530530
tags: Vec<String>,
531531
#[serde_as(as = "StringWithSeparator::<CommaSeparator, String>")]
532-
// more_tags: Vec<String>,
533532
more_tags: BTreeSet<String>,
533+
#[serde_as(as = "StringWithSeparator::<UnixLineSeparator, String>")]
534+
lf_tags: BTreeSet<String>,
535+
#[serde_as(as = "StringWithSeparator::<DosLineSeparator, String>")]
536+
crlf_tags: BTreeSet<String>,
534537
}
535538

536539
let v: A = serde_json::from_str(
537540
r##"{
538541
"tags": "#hello #world",
539-
"more_tags": "foo,bar,bar"
542+
"more_tags": "foo,bar,bar",
543+
"lf_tags": "foo\nbar\nbar",
544+
"crlf_tags": "foo\r\nbar\r\nbar"
540545
}"##,
541546
)
542547
.unwrap();
543548
assert_eq!(vec!["#hello", "#world"], v.tags);
544-
assert_eq!(2, v.more_tags.len());
549+
assert_eq!(
550+
BTreeSet::from(["foo".to_string(), "bar".to_string()]),
551+
v.more_tags
552+
);
553+
assert_eq!(
554+
BTreeSet::from(["foo".to_string(), "bar".to_string()]),
555+
v.lf_tags
556+
);
557+
assert_eq!(
558+
BTreeSet::from(["foo".to_string(), "bar".to_string()]),
559+
v.crlf_tags
560+
);
545561

546562
let x = A {
547563
tags: vec!["1".to_string(), "2".to_string(), "3".to_string()],
548564
more_tags: BTreeSet::default(),
565+
lf_tags: BTreeSet::default(),
566+
crlf_tags: BTreeSet::default(),
549567
};
550568
assert_eq!(
551-
r#"{"tags":"1 2 3","more_tags":""}"#,
569+
r#"{"tags":"1 2 3","more_tags":"","lf_tags":"","crlf_tags":""}"#,
552570
serde_json::to_string(&x).unwrap()
553571
);
554572
}

0 commit comments

Comments
 (0)