1 | use super::*; |
2 | |
3 | pub trait Write { |
4 | unsafe fn write_header<T: Sized>(&mut self, value: &T); |
5 | fn write_u8(&mut self, value: u8); |
6 | fn write_u16(&mut self, value: u16); |
7 | fn write_u32(&mut self, value: u32); |
8 | fn write_u64(&mut self, value: u64); |
9 | fn write_code(&mut self, value: u32, size: usize); |
10 | fn write_index(&mut self, index: u32, len: usize); |
11 | fn into_stream(self) -> Self; |
12 | } |
13 | |
14 | impl Write for Vec<u8> { |
15 | unsafe fn write_header<T: Sized>(&mut self, value: &T) { |
16 | self.extend_from_slice(std::slice::from_raw_parts(value as *const _ as _, std::mem::size_of::<T>())); |
17 | } |
18 | |
19 | fn write_u8(&mut self, value: u8) { |
20 | self.extend_from_slice(&value.to_le_bytes()); |
21 | } |
22 | |
23 | fn write_u16(&mut self, value: u16) { |
24 | self.extend_from_slice(&value.to_le_bytes()); |
25 | } |
26 | |
27 | fn write_u32(&mut self, value: u32) { |
28 | self.extend_from_slice(&value.to_le_bytes()); |
29 | } |
30 | |
31 | fn write_u64(&mut self, value: u64) { |
32 | self.extend_from_slice(&value.to_le_bytes()); |
33 | } |
34 | |
35 | fn write_code(&mut self, value: u32, size: usize) { |
36 | if size == 2 { |
37 | self.write_u16(value as u16); |
38 | } else { |
39 | self.write_u32(value); |
40 | } |
41 | } |
42 | |
43 | fn write_index(&mut self, index: u32, len: usize) { |
44 | if len < (1 << 16) { |
45 | self.write_u16(index as u16 + 1); |
46 | } else { |
47 | self.write_u32(index + 1); |
48 | } |
49 | } |
50 | |
51 | fn into_stream(mut self) -> Self { |
52 | self.resize(round(self.len(), 4), 0); |
53 | self |
54 | } |
55 | } |
56 | |
57 | pub trait Push2<T> { |
58 | fn push2(&mut self, value: T) -> u32; |
59 | } |
60 | |
61 | impl<T> Push2<T> for Vec<T> { |
62 | fn push2(&mut self, value: T) -> u32 { |
63 | self.push(value); |
64 | (self.len() - 1) as u32 |
65 | } |
66 | } |
67 | |