Skip to content

Commit e0667e9

Browse files
authored
Merge pull request #3 from containers/CanonJsonSerialize
Add CanonJsonSerialize trait
2 parents f0da6e0 + cc8729b commit e0667e9

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/lib.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,38 @@ impl Formatter for CanonicalFormatter {
351351
}
352352
}
353353

354+
pub trait CanonJsonSerialize {
355+
fn to_canon_json_writer<W>(&self, writer: W) -> Result<()>
356+
where
357+
W: Write;
358+
fn to_canon_json_vec(&self) -> Result<Vec<u8>>;
359+
fn to_canon_json_string(&self) -> Result<String>;
360+
}
361+
362+
impl<S> CanonJsonSerialize for S
363+
where
364+
S: Serialize,
365+
{
366+
fn to_canon_json_writer<W>(&self, writer: W) -> Result<()>
367+
where
368+
W: Write,
369+
{
370+
let mut ser = serde_json::Serializer::with_formatter(writer, CanonicalFormatter::new());
371+
Ok(self.serialize(&mut ser)?)
372+
}
373+
374+
fn to_canon_json_vec(&self) -> Result<Vec<u8>> {
375+
let mut buf = Vec::new();
376+
self.to_canon_json_writer(&mut buf)?;
377+
Ok(buf)
378+
}
379+
380+
fn to_canon_json_string(&self) -> Result<String> {
381+
String::from_utf8(self.to_canon_json_vec()?)
382+
.map_err(|err| Error::new(ErrorKind::InvalidData, err))
383+
}
384+
}
385+
354386
#[cfg(test)]
355387
mod tests {
356388
use super::*;

0 commit comments

Comments
 (0)