Skip to content

Commit

Permalink
Add Result serializer/deserializer
Browse files Browse the repository at this point in the history
Signed-off-by: Heinz N. Gies <[email protected]>
  • Loading branch information
Licenser committed Apr 3, 2023
1 parent 85fdb65 commit cf3d24d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
47 changes: 47 additions & 0 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,50 @@ where
}
}
}

impl<TOk, TErr> Serialize for std::result::Result<TOk, TErr>
where
TOk: Serialize,
TErr: Serialize,
{
#[inline]
fn json_write<W>(&self, writer: &mut W) -> io::Result<()>
where
W: Write,
{
match self {
Ok(e) => {
writer.write_all(b"{\"ok\":")?;
e.json_write(writer)?;
writer.write_all(b"}")
}
Err(e) => {
writer.write_all(b"{\"err\":")?;
e.json_write(writer)?;
writer.write_all(b"}")
}
}
}
}

impl<'input, TOk, TErr> Deserialize<'input> for std::result::Result<TOk, TErr>
where
TOk: Deserialize<'input>,
TErr: Deserialize<'input>,
{
#[inline]
fn from_tape(tape: &mut Tape<'input>) -> simd_json::Result<Self>
where
Self: std::marker::Sized + 'input,
{
if let Some(simd_json::Node::Object(1, _)) = tape.next() {
match tape.next() {
Some(simd_json::Node::String("ok")) => Ok(Ok(TOk::from_tape(tape)?)),
Some(simd_json::Node::String("err")) => Ok(Err(TErr::from_tape(tape)?)),
_ => Err(simd_json::Error::generic(simd_json::ErrorType::ExpectedMap)),
}
} else {
Err(simd_json::Error::generic(simd_json::ErrorType::ExpectedMap))
}
}
}
19 changes: 18 additions & 1 deletion tests/deser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,13 @@ fn event() {

#[test]
fn enum_ser() {
#[derive(Deserialize, PartialEq, Eq, Debug)]
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]
pub enum StoredVariants {
YesNo(bool),
Small(u8, i8),
Signy(i64),
Stringy(String),
Res(Result<u8, String>),
}

let mut s = String::from(r#"{"Small":[1,2]}"#);
Expand All @@ -139,4 +140,20 @@ fn enum_ser() {
let mut s = String::from(r#"{"YesNo":true}"#);
let e = StoredVariants::from_str(s.as_mut_str()).unwrap();
assert_eq!(StoredVariants::YesNo(true), e);

let mut s = String::from(r#"{"Res":{"ok":42}}"#);
let e = StoredVariants::from_str(s.as_mut_str()).unwrap();
assert_eq!(StoredVariants::Res(Ok(42)), e);

let mut s = String::from(r#"{"Res":{"err":"snot"}}"#);
let e = StoredVariants::from_str(s.as_mut_str()).unwrap();
assert_eq!(StoredVariants::Res(Err(String::from("snot"))), e);

let e = StoredVariants::Res(Ok(42)).json_string().unwrap();
assert_eq!(r#"{"Res":{"ok":42}}"#, e);

let e = StoredVariants::Res(Err(String::from("snot")))
.json_string()
.unwrap();
assert_eq!(r#"{"Res":{"err":"snot"}}"#, e);
}

0 comments on commit cf3d24d

Please sign in to comment.