Skip to content

Commit

Permalink
feat: Help write decoders/encoders
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Aug 10, 2021
1 parent df1c5c7 commit f72100b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/encoded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ pub enum Encoded {
}

impl Encoded {
pub fn from_slice(v: &[u8]) -> Result<Self, serde_json::Error> {
serde_json::from_slice(v)
pub fn from_slice(v: &[u8]) -> Result<Self, crate::Error> {
serde_json::from_slice(v).map_err(|e| crate::Error::new(e.to_string()))
}

pub fn to_string_pretty(&self) -> Result<String, crate::Error> {
serde_json::to_string_pretty(self).map_err(|e| crate::Error::new(e.to_string()))
}
}

Expand Down
20 changes: 20 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -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 {}
21 changes: 21 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<encoded::Encoded, Error> {
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()))
}

0 comments on commit f72100b

Please sign in to comment.