subsetter/
write.rs

1/// A writable stream of binary data.
2pub struct Writer(Vec<u8>);
3
4impl Writer {
5    /// Create a new writable stream of binary data.
6    #[inline]
7    pub fn new() -> Self {
8        Self(Vec::with_capacity(1024))
9    }
10
11    /// Create a new writable stream of binary data with a capacity.
12    #[inline]
13    pub fn with_capacity(capacity: usize) -> Self {
14        Self(Vec::with_capacity(capacity))
15    }
16
17    /// Write `T` into the data.
18    #[inline]
19    pub fn write<T: Writeable>(&mut self, data: T) {
20        data.write(self);
21    }
22
23    /// Give bytes into the writer.
24    #[inline]
25    pub fn extend(&mut self, bytes: &[u8]) {
26        self.0.extend(bytes);
27    }
28
29    /// Align the contents to a byte boundary.
30    #[inline]
31    pub fn align(&mut self, to: usize) {
32        while self.0.len() % to != 0 {
33            self.0.push(0);
34        }
35    }
36
37    /// The number of written bytes.
38    #[inline]
39    pub fn len(&self) -> usize {
40        self.0.len()
41    }
42
43    /// Return the written bytes.
44    #[inline]
45    pub fn finish(self) -> Vec<u8> {
46        self.0
47    }
48}
49
50/// Trait for an object that can be written into a byte stream.
51pub trait Writeable: Sized {
52    fn write(&self, w: &mut Writer);
53}
54
55impl<T: Writeable, const N: usize> Writeable for [T; N] {
56    fn write(&self, w: &mut Writer) {
57        for i in self {
58            w.write(i);
59        }
60    }
61}
62
63impl Writeable for u8 {
64    fn write(&self, w: &mut Writer) {
65        w.extend(&self.to_be_bytes());
66    }
67}
68
69impl<T> Writeable for &[T]
70where
71    T: Writeable,
72{
73    fn write(&self, w: &mut Writer) {
74        for el in *self {
75            w.write(el);
76        }
77    }
78}
79
80impl<T> Writeable for &T
81where
82    T: Writeable,
83{
84    fn write(&self, w: &mut Writer) {
85        T::write(self, w)
86    }
87}
88
89impl Writeable for u16 {
90    fn write(&self, w: &mut Writer) {
91        w.write::<[u8; 2]>(self.to_be_bytes());
92    }
93}
94
95impl Writeable for i16 {
96    fn write(&self, w: &mut Writer) {
97        w.write::<[u8; 2]>(self.to_be_bytes());
98    }
99}
100
101impl Writeable for u32 {
102    fn write(&self, w: &mut Writer) {
103        w.write::<[u8; 4]>(self.to_be_bytes());
104    }
105}
106
107impl Writeable for i32 {
108    fn write(&self, w: &mut Writer) {
109        w.write::<[u8; 4]>(self.to_be_bytes());
110    }
111}