use core::{error, fmt};
use std::io::{self, Read, Write};
use crate::{PlainOldData, RawRepr, TryFromRawRepr, byteable_trait::DecodeError};
#[derive(Debug)]
pub enum ReadableError {
Io(std::io::Error),
DecodeError(DecodeError),
}
impl fmt::Display for ReadableError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ReadableError::Io(error) => error.fmt(f),
ReadableError::DecodeError(decode_error) => decode_error.fmt(f),
}
}
}
impl error::Error for ReadableError {}
impl From<std::io::Error> for ReadableError {
#[inline]
fn from(value: std::io::Error) -> Self {
Self::Io(value)
}
}
impl From<DecodeError> for ReadableError {
#[inline]
fn from(value: DecodeError) -> Self {
Self::DecodeError(value)
}
}
pub trait FixedReadable: Sized {
fn read_fixed_from(reader: &mut (impl Read + ?Sized)) -> Result<Self, ReadableError>;
}
impl<T: TryFromRawRepr> FixedReadable for T {
#[inline]
fn read_fixed_from(reader: &mut (impl Read + ?Sized)) -> Result<Self, ReadableError> {
let mut b = T::Raw::zeroed();
reader.read_exact(b.as_bytes_mut())?;
let r = T::try_from_raw(b)?;
Ok(r)
}
}
pub trait Readable: Sized {
fn read_from(reader: &mut (impl Read + ?Sized)) -> Result<Self, ReadableError>;
}
impl<T: FixedReadable> Readable for T {
#[inline]
fn read_from(reader: &mut (impl Read + ?Sized)) -> Result<Self, ReadableError> {
T::read_fixed_from(reader)
}
}
pub trait FixedWritable {
fn write_fixed_to(&self, writer: &mut (impl Write + ?Sized)) -> io::Result<()>;
}
impl<T: RawRepr> FixedWritable for T {
#[inline]
fn write_fixed_to(&self, writer: &mut (impl Write + ?Sized)) -> io::Result<()> {
let raw = self.to_raw();
writer.write_all(raw.as_bytes())
}
}
pub trait Writable {
fn write_to(&self, writer: &mut (impl Write + ?Sized)) -> io::Result<()>;
}
impl<T: FixedWritable> Writable for T {
#[inline]
fn write_to(&self, writer: &mut (impl Write + ?Sized)) -> io::Result<()> {
self.write_fixed_to(writer)
}
}
pub trait ReadFixed: Read {
#[inline]
fn read_fixed<T: FixedReadable>(&mut self) -> Result<T, ReadableError> {
T::read_fixed_from(self)
}
}
impl<T: Read + ?Sized> ReadFixed for T {}
pub trait ReadValue: Read {
#[inline]
fn read_value<T: Readable>(&mut self) -> Result<T, ReadableError> {
T::read_from(self)
}
}
impl<T: Read> ReadValue for T {}
pub trait WriteFixed: Write {
#[inline]
fn write_fixed(&mut self, val: &impl FixedWritable) -> io::Result<()> {
val.write_fixed_to(self)
}
}
impl<T: Write> WriteFixed for T {}
pub trait WriteValue: Write {
#[inline]
fn write_value<T: Writable + ?Sized>(&mut self, data: &T) -> io::Result<()> {
data.write_to(self)
}
}
impl<T: Write> WriteValue for T {}