omnom/
write_bytes.rs

1use std::io::{self, Write};
2
3/// Trait to enable writing bytes to a writer.
4pub trait WriteBytes {
5    /// Write bytes to a writer as big endian.
6    ///
7    /// Returns the amount of bytes written.
8    fn write_be_bytes<W: Write>(&self, writer: &mut W) -> io::Result<usize>;
9
10    /// Write bytes to a writer as little endian.
11    ///
12    /// Returns the amount of bytes written.
13    fn write_le_bytes<W: Write>(&self, writer: &mut W) -> io::Result<usize>;
14
15    /// Write bytes to a writer using native endianness.
16    ///
17    /// Returns the amount of bytes written.
18    fn write_ne_bytes<W: Write>(&self, writer: &mut W) -> io::Result<usize>;
19}
20
21macro_rules! doc_comment {
22    ($x:expr, $($tt:tt)*) => {
23        #[doc = $x]
24        $($tt)*
25    };
26}
27
28macro_rules! write_bytes_impl {
29    ($($SelfT:ty),* $(,)?) => { $(
30        impl WriteBytes for $SelfT {
31        doc_comment! {
32            concat!("Write bytes to a writer as big endian.
33
34# Examples
35
36```
37use std::io::Cursor;
38use omnom::prelude::*;
39
40let mut buf = Cursor::new(vec![0; 15]);
41
42let num = 12_", stringify!($SelfT), ";
43buf.write_be(num).unwrap();
44```"),
45            fn write_be_bytes<W: Write>(&self, writer: &mut W) -> io::Result<usize> {
46                let b = &self.to_be_bytes();
47                let len = b.len();
48                writer.write_all(b)?;
49                Ok(len)
50            }
51        }
52
53        doc_comment! {
54            concat!("Write bytes to a writer as little endian.
55
56# Examples
57
58```
59use std::io::Cursor;
60use omnom::prelude::*;
61
62let mut buf = Cursor::new(vec![0; 15]);
63
64let num = 12_", stringify!($SelfT), ";
65buf.write_le(num).unwrap();
66```"),
67            fn write_le_bytes<W: Write>(&self, writer: &mut W) -> io::Result<usize> {
68                let b = &self.to_le_bytes();
69                let len = b.len();
70                writer.write_all(b)?;
71                Ok(len)
72            }
73        }
74
75        doc_comment! {
76            concat!("Write bytes to a writer using native endianness.
77
78As the target platform's native endianness is used, portable code
79likely wants to use [`write_be_bytes`] or [`write_le_bytes`], as
80appropriate instead.
81
82[`write_be_bytes`]: #method.write_be_bytes
83[`write_le_bytes`]: #method.write_le_bytes
84
85# Examples
86
87```
88use std::io::Cursor;
89use omnom::prelude::*;
90
91let mut buf = Cursor::new(vec![0; 15]);
92
93let num = 12_", stringify!($SelfT), ";
94buf.write_ne(num).unwrap();
95```"),
96            fn write_ne_bytes<W: Write>(&self, writer: &mut W) -> io::Result<usize> {
97                let b = &self.to_ne_bytes();
98                let len = b.len();
99                writer.write_all(b)?;
100                Ok(len)
101            }
102        }
103    }
104)*}}
105
106write_bytes_impl!(u8, u16, u32, u64, u128, usize);
107write_bytes_impl!(i8, i16, i32, i64, i128, isize);