From f72100b83d79e929e1952dbcb757dca47708a37e Mon Sep 17 00:00:00 2001 From: Ed Page Date: Tue, 10 Aug 2021 14:59:35 -0500 Subject: [PATCH] feat: Help write decoders/encoders --- src/encoded.rs | 8 ++++++-- src/error.rs | 20 ++++++++++++++++++++ src/lib.rs | 21 +++++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 src/error.rs diff --git a/src/encoded.rs b/src/encoded.rs index fc013ba..ba79d78 100644 --- a/src/encoded.rs +++ b/src/encoded.rs @@ -7,8 +7,12 @@ pub enum Encoded { } impl Encoded { - pub fn from_slice(v: &[u8]) -> Result { - serde_json::from_slice(v) + pub fn from_slice(v: &[u8]) -> Result { + serde_json::from_slice(v).map_err(|e| crate::Error::new(e.to_string())) + } + + pub fn to_string_pretty(&self) -> Result { + serde_json::to_string_pretty(self).map_err(|e| crate::Error::new(e.to_string())) } } diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..e464738 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,20 @@ +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error { + message: String, +} + +impl Error { + pub fn new(message: impl ToString) -> Self { + Self { + message: message.to_string(), + } + } +} + +impl std::fmt::Display for Error { + fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + self.message.fmt(formatter) + } +} + +impl std::error::Error for Error {} diff --git a/src/lib.rs b/src/lib.rs index 2bd3a8a..dffd25b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,22 @@ +use std::io::Read; +use std::io::Write; + +mod error; + pub mod encoded; +pub use error::Error; + +pub fn encoder_in() -> Result { + let mut buf = Vec::new(); + std::io::stdin() + .read_to_end(&mut buf) + .map_err(|e| crate::Error::new(e.to_string()))?; + encoded::Encoded::from_slice(&buf) +} + +pub fn decoder_output(e: encoded::Encoded) -> Result<(), Error> { + let s = e.to_string_pretty()?; + std::io::stdout() + .write_all(s.as_bytes()) + .map_err(|e| crate::Error::new(e.to_string())) +}