Skip to content

Commit

Permalink
Implement SerJson for str
Browse files Browse the repository at this point in the history
  • Loading branch information
hoangdt84 authored and not-fl3 committed Jul 15, 2023
1 parent 0517a26 commit c873704
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 18 deletions.
43 changes: 25 additions & 18 deletions src/serde_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -778,29 +778,36 @@ impl DeJson for bool {
}
}

impl SerJson for String {
fn ser_json(&self, _d: usize, s: &mut SerJsonState) {
s.out.push('"');
for c in self.chars() {
match c {
'\x08' => s.out += "\\b",
'\x0C' => s.out += "\\f",
'\n' => s.out += "\\n",
'\r' => s.out += "\\r",
'\t' => s.out += "\\t",
_ if c.is_ascii_control() => {
use core::fmt::Write as _;
let _ = write!(s.out, "\\u{:04x}", c as u32);
macro_rules! impl_ser_json_string {
($ty: ident) => {
impl SerJson for $ty {
fn ser_json(&self, _d: usize, s: &mut SerJsonState) {
s.out.push('"');
for c in self.chars() {
match c {
'\x08' => s.out += "\\b",
'\x0C' => s.out += "\\f",
'\n' => s.out += "\\n",
'\r' => s.out += "\\r",
'\t' => s.out += "\\t",
_ if c.is_ascii_control() => {
use core::fmt::Write as _;
let _ = write!(s.out, "\\u{:04x}", c as u32);
}
'\\' => s.out += "\\\\",
'"' => s.out += "\\\"",
_ => s.out.push(c),
}
}
'\\' => s.out += "\\\\",
'"' => s.out += "\\\"",
_ => s.out.push(c),
s.out.push('"');
}
}
s.out.push('"');
}
};
}

impl_ser_json_string!(String);
impl_ser_json_string!(str);

impl DeJson for String {
fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<String, DeJsonErr> {
let val = s.as_string()?;
Expand Down
38 changes: 38 additions & 0 deletions tests/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -691,3 +691,41 @@ fn control_characters() {

assert_eq!(SerJson::serialize_json(&string), escaped);
}

#[test]
fn ser_str() {
#[derive(SerJson)]
struct AString {
s: String,
}

#[derive(SerJson)]
struct ABorrowedString<'a> {
s: &'a String,
}

#[derive(SerJson)]
struct AStr<'a> {
s: &'a str,
}

let a_string = AString {
s: "abc".to_string(),
};

let a_borrowed_string = ABorrowedString {
s: &"abc".to_string(),
};

let a_str = AStr { s: "abc" };

assert_eq!(
SerJson::serialize_json(&a_string),
SerJson::serialize_json(&a_borrowed_string)
);

assert_eq!(
SerJson::serialize_json(&a_string),
SerJson::serialize_json(&a_str)
);
}

0 comments on commit c873704

Please sign in to comment.