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
use std::io::{Result, Write};
use crate::VariableWritable;

include!("writer_bools.rs");
include!("writer_raw.rs");
include!("writer_varint.rs");
include!("writer_signed.rs");
include!("writer_float.rs");

pub trait VariableWriter: VariableWritable {
    #[inline]
    fn write_bool(&mut self, b: bool) -> Result<usize> {
        self.write_single(if b { 1 } else { 0 })
    }

    define_write_bools!();
    define_write_raw!();
    define_write_varint!();
    define_write_signed!();
    define_write_float!();

    #[cfg(feature = "vec_u8")]
    #[cfg_attr(docsrs, doc(cfg(feature = "vec_u8")))]
    #[inline]
    fn write_u8_vec(&mut self, message: &[u8]) -> Result<usize> {
        self.write_usize_varint(message.len())?;
        self.write_more(message)
    }

    #[cfg(feature = "string")]
    #[cfg_attr(docsrs, doc(cfg(feature = "string")))]
    #[inline]
    fn write_string(&mut self, message: &str) -> Result<usize> {
        self.write_u8_vec(message.as_bytes())
    }
}

impl<W: VariableWritable> VariableWriter for W {
}

impl<W: Write> VariableWritable for W {
    #[inline]
    fn write_single(&mut self, byte: u8) -> Result<usize> {
        W::write_all(self, &[byte])?;
        Ok(1)
    }

    #[inline]
    fn write_more(&mut self, buf: &[u8]) -> Result<usize> {
        W::write_all(self, buf)?;
        Ok(buf.len())
    }
}