typed_io/
write_bytes.rs

1use crate::Endianness;
2use std::io::{Result, Write};
3
4/// This trait is to write an endianness fixed-length bytes.
5pub trait WriteEndianness {
6    fn write_endianness_with_callback<F, W: Write>(
7        &self,
8        writer: &mut W,
9        callback: F,
10        endianness: Endianness,
11    ) -> Result<()>
12    where
13        F: Fn(&mut [u8]);
14
15    /// This method writes bytes in big-endian byte order.
16    fn write_be_bytes<W: Write>(&self, writer: &mut W) -> Result<()> {
17        self.write_endianness_with_callback(writer, |_| {}, Endianness::BE)
18    }
19    /// This method writes bytes in little-endian byte order.
20    fn write_le_bytes<W: Write>(&self, writer: &mut W) -> Result<()> {
21        self.write_endianness_with_callback(writer, |_| {}, Endianness::LE)
22    }
23    /// This method writes bytes in little-endian byte order.
24    ///
25    /// As the target platform’s native endianness is used, portable code should use write_be_bytes or write_le_bytes, as appropriate, instead.
26    fn write_ne_bytes<W: Write>(&self, writer: &mut W) -> Result<()> {
27        self.write_endianness_with_callback(writer, |_| {}, Endianness::NE)
28    }
29}
30
31macro_rules! write_endianness_impl {
32    ( $( $t:ty ),* ) => ($(
33        impl WriteEndianness for $t {
34            fn write_endianness_with_callback<F, W: Write>(&self, writer: &mut W, callback: F,
35                endianness: Endianness) -> Result<()> where F: Fn(&mut [u8]) {
36                let bytes = &mut match endianness {
37                    Endianness::BE => self.to_be_bytes(),
38                    Endianness::LE => self.to_le_bytes(),
39                    Endianness::NE => self.to_ne_bytes(),
40                };
41                callback(bytes);
42                writer.write_all(bytes)?;
43                Ok(())
44            }
45        }
46    )*)
47}
48
49write_endianness_impl!(f32, f64);
50write_endianness_impl!(isize, i8, i16, i32, i64, i128);
51write_endianness_impl!(usize, u8, u16, u32, u64, u128);
52
53pub trait WriteRef {
54    fn write_ref_bytes_with_callback<F, W: Write>(&self, writer: &mut W, callback: F) -> Result<()>
55    where
56        F: Fn(&[u8]);
57
58    fn write_ref_bytes<W: Write>(&self, writer: &mut W) -> Result<()> {
59        self.write_ref_bytes_with_callback(writer, |_| {})
60    }
61}
62impl WriteRef for [u8] {
63    fn write_ref_bytes_with_callback<F, W: Write>(&self, writer: &mut W, callback: F) -> Result<()>
64    where
65        F: Fn(&[u8]),
66    {
67        callback(self);
68        writer.write_all(self)?;
69        Ok(())
70    }
71}
72impl WriteRef for str {
73    fn write_ref_bytes_with_callback<F, W: Write>(&self, writer: &mut W, callback: F) -> Result<()>
74    where
75        F: Fn(&[u8]),
76    {
77        let bytes = self.as_bytes();
78        callback(bytes);
79        writer.write_all(bytes)?;
80        Ok(())
81    }
82}