rw-types 0.2.0

Library for reading and writing types.
Documentation
use std::io;

use crate::{Endian, write::WriteExt};

/// A trait for objects that can be written.
pub trait Writable: Sized {
    /// Writes this object with the specified writer and endian.
    fn write(&self, writer: impl WriteExt, endian: Endian) -> io::Result<()>;
}

macro_rules! num {
    (impl $ty:ty) => {
        impl Writable for $ty {
            fn write(&self, mut writer: impl WriteExt, endian: Endian) -> io::Result<()> {
                let bytes = match endian {
                    Endian::Big => self.to_be_bytes(),
                    Endian::Little => self.to_le_bytes(),
                    Endian::Native => self.to_ne_bytes(),
                };
                writer.write_all(&bytes)?;
                Ok(())
            }
        }
    };
    ($($ty:ty)+) => {
        $( num!(impl $ty); )+
    };
}

num!(u8 u16 u32 u64 u128);
num!(i8 i16 i32 i64 i128);
num!(f32 f64);

impl Writable for bool {
    fn write(&self, mut writer: impl WriteExt, endian: Endian) -> io::Result<()> {
        let value = if *self { 1 } else { 0 };
        writer.write_ty::<u8>(&value, endian)?;
        Ok(())
    }
}