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