it_to_bytes/
lib.rs

1use std::io;
2use std::io::Write;
3
4/// A trait for converting a value to bytes.
5pub trait ToBytes<W>
6where
7    W: Write,
8{
9    /// Converts the given value into `&[u8]` in the given `writer`.
10    fn to_bytes(&self, writer: &mut W) -> io::Result<()>;
11}
12
13/// Encode a `u8` into a byte (well, it's already a byte!).
14impl<W> ToBytes<W> for u8
15where
16    W: Write,
17{
18    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
19        writer.write_all(&[*self])
20    }
21}
22
23/// Encode a `u64` into bytes with a LEB128 representation.
24///
25/// Decoder is `decoders::binary::uleb`.
26impl<W> ToBytes<W> for u64
27where
28    W: Write,
29{
30    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
31        let mut value = *self;
32
33        // Code adapted from the Rust' `serialize` library.
34        loop {
35            if value < 0x80 {
36                writer.write_all(&[value as u8])?;
37
38                break;
39            }
40
41            writer.write_all(&[((value & 0x7f) | 0x80) as u8])?;
42            value >>= 7;
43        }
44
45        Ok(())
46    }
47}
48
49/// Encode a `str` into bytes.
50///
51/// Decoder is `decoders::binary::string`.
52impl<W> ToBytes<W> for &str
53where
54    W: Write,
55{
56    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
57        // Size first.
58        writer.write_all(&[self.len() as u8])?;
59
60        // Then the string.
61        writer.write_all(self.as_bytes())?;
62
63        Ok(())
64    }
65}
66
67/// Encode a String into bytes.
68///
69/// Decoder is `decoders::binary::string`.
70impl<W> ToBytes<W> for String
71where
72    W: Write,
73{
74    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
75        // Size first.
76        writer.write_all(&[self.len() as u8])?;
77
78        // Then the string.
79        writer.write_all(self.as_bytes())?;
80
81        Ok(())
82    }
83}
84
85/// Encode a vector into bytes.
86///
87/// Decoder is `decoders::binary::list`.
88impl<W, I> ToBytes<W> for Vec<I>
89where
90    W: Write,
91    I: ToBytes<W>,
92{
93    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
94        // Size first.
95        (self.len() as u64).to_bytes(writer)?;
96
97        // Then the items.
98        for item in self {
99            item.to_bytes(writer)?;
100        }
101
102        Ok(())
103    }
104}