use sysexits::{ExitCode, Result};
pub trait Buffer {
fn try_from_bytes(&mut self, bytes: &[u8]) -> Result<()>;
fn try_from_string(&mut self, string: &str) -> Result<()>;
fn try_into_bytes(&self) -> Result<Vec<u8>>;
fn try_into_string(&self) -> Result<String>;
}
impl Buffer for String {
fn try_from_bytes(&mut self, bytes: &[u8]) -> Result<()> {
Self::from_utf8(bytes.to_vec()).map_or(
Err(ExitCode::DataErr),
|string| {
*self = string;
Ok(())
},
)
}
fn try_from_string(&mut self, string: &str) -> Result<()> {
*self = string.to_string();
Ok(())
}
fn try_into_bytes(&self) -> Result<Vec<u8>> {
Ok(self.as_bytes().to_vec())
}
fn try_into_string(&self) -> Result<String> {
Ok(self.clone())
}
}
impl Buffer for Vec<u8> {
fn try_from_bytes(&mut self, bytes: &[u8]) -> Result<()> {
*self = bytes.to_vec();
Ok(())
}
fn try_from_string(&mut self, string: &str) -> Result<()> {
*self = string.as_bytes().to_vec();
Ok(())
}
fn try_into_bytes(&self) -> Result<Vec<u8>> {
Ok(self.clone())
}
fn try_into_string(&self) -> Result<String> {
String::from_utf8(self.clone()).map_or(Err(ExitCode::DataErr), Ok)
}
}