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
//! Generic utilities

use std::io::{self, Write};

/// Source: <https://stackoverflow.com/questions/42187591/>
pub struct ByteCounter<W> {
    inner: W,
    count: usize,
}

impl<W> ByteCounter<W>
where
    W: Write,
{
    /// Create a new byte counter
    pub fn new(inner: W) -> Self {
        ByteCounter { inner, count: 0 }
    }

    /// Return the inner writer
    pub fn into_inner(self) -> W {
        self.inner
    }

    /// Get the number of bytes written
    pub fn bytes_written(&self) -> usize {
        self.count
    }
}

impl<W> Write for ByteCounter<W>
where
    W: Write,
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let res = self.inner.write(buf);
        if let Ok(size) = res {
            self.count += size
        }
        res
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

pub(crate) struct NextID {
    obj_id: u64,
}

impl NextID {
    pub(crate) fn new(start: u64) -> Self {
        Self { obj_id: start }
    }

    pub(crate) fn next(&mut self) -> u64 {
        let next = self.obj_id;
        self.obj_id += 1;
        next
    }
}