pub mod default_formats;
pub use self::default_formats::PlainBytes;
pub use self::default_formats::PlainUtf8;
use std::io::{Cursor, BufReader, BufWriter, Read, Write};
#[allow(clippy::wrong_self_convention)]
pub trait FileFormat<T> {
type FormatError: std::error::Error;
fn from_reader<R: Read>(&self, reader: R) -> Result<T, Self::FormatError>;
#[inline]
fn from_reader_buffered<R: Read>(&self, reader: R) -> Result<T, Self::FormatError> {
self.from_reader(BufReader::new(reader))
}
#[inline]
fn from_buffer(&self, buf: &[u8]) -> Result<T, Self::FormatError> {
self.from_reader(buf)
}
fn to_writer<W: Write>(&self, writer: W, value: &T) -> Result<(), Self::FormatError>;
#[inline]
fn to_writer_buffered<W: Write>(&self, writer: W, value: &T) -> Result<(), Self::FormatError> {
self.to_writer(BufWriter::new(writer), value)
}
fn to_buffer(&self, value: &T) -> Result<Vec<u8>, Self::FormatError> {
let mut buf = Cursor::new(Vec::new());
self.to_writer(&mut buf, value)?;
Ok(buf.into_inner())
}
}
#[allow(clippy::wrong_self_convention)]
pub trait FileFormatUtf8<T>: FileFormat<T> {
fn from_string_buffer(&self, buf: &str) -> Result<T, Self::FormatError>;
fn to_string_buffer(&self, value: &T) -> Result<String, Self::FormatError>;
}
macro_rules! impl_file_format_delegate {
(<$Format:ident> $Type:ty) => (
impl<T, $Format: FileFormat<T>> FileFormat<T> for $Type {
type FormatError = <$Format as FileFormat<T>>::FormatError;
#[inline]
fn from_reader_buffered<R: Read>(&self, reader: R) -> Result<T, Self::FormatError> {
$Format::from_reader_buffered(self, reader)
}
#[inline]
fn from_reader<R: Read>(&self, reader: R) -> Result<T, Self::FormatError> {
$Format::from_reader(self, reader)
}
#[inline]
fn from_buffer(&self, buf: &[u8]) -> Result<T, Self::FormatError> {
$Format::from_buffer(self, buf)
}
#[inline]
fn to_writer<W: Write>(&self, writer: W, value: &T) -> Result<(), Self::FormatError> {
$Format::to_writer(self, writer, value)
}
#[inline]
fn to_writer_buffered<W: Write>(&self, writer: W, value: &T) -> Result<(), Self::FormatError> {
$Format::to_writer_buffered(self, writer, value)
}
#[inline]
fn to_buffer(&self, value: &T) -> Result<Vec<u8>, Self::FormatError> {
$Format::to_buffer(self, value)
}
}
impl<T, $Format: FileFormatUtf8<T>> FileFormatUtf8<T> for $Type {
fn from_string_buffer(&self, buf: &str) -> Result<T, Self::FormatError> {
$Format::from_string_buffer(self, buf)
}
fn to_string_buffer(&self, value: &T) -> Result<String, Self::FormatError> {
$Format::to_string_buffer(self, value)
}
}
);
}
impl_file_format_delegate!(<Format> &Format);
impl_file_format_delegate!(<Format> std::boxed::Box<Format>);
impl_file_format_delegate!(<Format> std::rc::Rc<Format>);
impl_file_format_delegate!(<Format> std::sync::Arc<Format>);