Skip to main content

rw_types/write/
writable.rs

1use std::io;
2
3use crate::{Endian, write::WriteExt};
4
5/// A trait for objects that can be written.
6pub trait Writable: Sized {
7    /// Writes this object with the specified writer and endian.
8    fn write(&self, writer: impl WriteExt, endian: Endian) -> io::Result<()>;
9}
10
11macro_rules! num {
12    (impl $ty:ty) => {
13        impl Writable for $ty {
14            fn write(&self, mut writer: impl WriteExt, endian: Endian) -> io::Result<()> {
15                let bytes = match endian {
16                    Endian::Big => self.to_be_bytes(),
17                    Endian::Little => self.to_le_bytes(),
18                    Endian::Native => self.to_ne_bytes(),
19                };
20                writer.write_all(&bytes)?;
21                Ok(())
22            }
23        }
24    };
25    ($($ty:ty)+) => {
26        $( num!(impl $ty); )+
27    };
28}
29
30num!(u8 u16 u32 u64 u128);
31num!(i8 i16 i32 i64 i128);
32num!(f32 f64);
33
34impl Writable for bool {
35    fn write(&self, mut writer: impl WriteExt, endian: Endian) -> io::Result<()> {
36        let value = if *self { 1 } else { 0 };
37        writer.write_ty::<u8>(&value, endian)?;
38        Ok(())
39    }
40}