1pub struct Writer(Vec<u8>);
3
4impl Writer {
5 #[inline]
7 pub fn new() -> Self {
8 Self(Vec::with_capacity(1024))
9 }
10
11 #[inline]
13 pub fn with_capacity(capacity: usize) -> Self {
14 Self(Vec::with_capacity(capacity))
15 }
16
17 #[inline]
19 pub fn write<T: Writeable>(&mut self, data: T) {
20 data.write(self);
21 }
22
23 #[inline]
25 pub fn extend(&mut self, bytes: &[u8]) {
26 self.0.extend(bytes);
27 }
28
29 #[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 #[inline]
39 pub fn len(&self) -> usize {
40 self.0.len()
41 }
42
43 #[inline]
45 pub fn finish(self) -> Vec<u8> {
46 self.0
47 }
48}
49
50pub 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}