-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.rs
64 lines (55 loc) · 1.17 KB
/
writer.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
use crate::{DynamicStructIndexWriter, Position, Write};
use std::{collections::HashMap, convert::TryInto};
pub struct Writer {
indexes: HashMap<DynamicStructIndexWriter, Position<DynamicStructIndexWriter>>,
buffer: Vec<u8>,
}
impl Default for Writer {
fn default() -> Self {
Writer::new()
}
}
impl Writer {
pub fn new() -> Writer {
Writer {
indexes: HashMap::new(),
buffer: Vec::new(),
}
}
pub fn position<T>(&self) -> Position<T>
where
T: ?Sized,
{
Position::new(self.buffer.len().try_into().unwrap())
}
pub fn write_raw<T>(&mut self, bytes: &[u8]) -> Position<T::Output>
where
T: Write + ?Sized,
{
let position = self.position();
self.buffer.extend(bytes);
position
}
pub fn write<T>(&mut self, value: &T) -> Position<T::Output>
where
T: Write + ?Sized,
{
value.write(self)
}
pub fn add_index(
&mut self,
index: DynamicStructIndexWriter,
position: Position<DynamicStructIndexWriter>,
) {
self.indexes.insert(index, position);
}
pub fn get_index(
&self,
index: &DynamicStructIndexWriter,
) -> Option<&Position<DynamicStructIndexWriter>> {
self.indexes.get(index)
}
pub fn into_bytes(self) -> Vec<u8> {
self.buffer
}
}