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
use super::Control;
use byteorder::{LittleEndian, WriteBytesExt};
use integer_encoding::VarIntWriter;
use std::io::{self, Write};

pub const MAGIC: u32 = 0xB1DF;
pub const VERSION: u32 = 0x1000;

pub struct Writer<W>
where
    W: Write,
{
    w: W,
}

impl<W> Writer<W>
where
    W: Write,
{
    pub fn new(mut w: W) -> Result<Self, io::Error> {
        w.write_u32::<LittleEndian>(MAGIC)?;
        w.write_u32::<LittleEndian>(VERSION)?;

        Ok(Self { w })
    }

    pub fn write(&mut self, c: &Control) -> Result<(), io::Error> {
        let w = &mut self.w;

        w.write_varint(c.add.len())?;
        w.write_all(c.add)?;

        w.write_varint(c.copy.len())?;
        w.write_all(c.copy)?;

        w.write_varint(c.seek)?;

        Ok(())
    }

    pub fn flush(&mut self) -> Result<(), io::Error> {
        self.w.flush()
    }

    pub fn into_inner(self) -> W {
        self.w
    }
}