1use crate::{DynamicStructIndexWriter, Position, Write};
2use std::{collections::HashMap, convert::TryInto};
3
4pub struct Writer {
5 indexes: HashMap<DynamicStructIndexWriter, Position<DynamicStructIndexWriter>>,
6 buffer: Vec<u8>,
7}
8
9impl Default for Writer {
10 fn default() -> Self {
11 Writer::new()
12 }
13}
14
15impl Writer {
16 pub fn new() -> Writer {
17 Writer {
18 indexes: HashMap::new(),
19 buffer: Vec::new(),
20 }
21 }
22
23 pub fn position<T>(&self) -> Position<T>
24 where
25 T: ?Sized,
26 {
27 Position::new(self.buffer.len().try_into().unwrap())
28 }
29
30 pub fn write_raw<T>(&mut self, bytes: &[u8]) -> Position<T::Output>
31 where
32 T: Write + ?Sized,
33 {
34 let position = self.position();
35 self.buffer.extend(bytes);
36 position
37 }
38
39 pub fn write<T>(&mut self, value: &T) -> Position<T::Output>
40 where
41 T: Write + ?Sized,
42 {
43 value.write(self)
44 }
45
46 pub fn add_index(
47 &mut self,
48 index: DynamicStructIndexWriter,
49 position: Position<DynamicStructIndexWriter>,
50 ) {
51 self.indexes.insert(index, position);
52 }
53
54 pub fn get_index(
55 &self,
56 index: &DynamicStructIndexWriter,
57 ) -> Option<&Position<DynamicStructIndexWriter>> {
58 self.indexes.get(index)
59 }
60
61 pub fn into_bytes(self) -> Vec<u8> {
62 self.buffer
63 }
64}