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
/// Serialisation mechanism that is chosen over bytestring concatenation
/// both for performance and simplicity.
///
/// See [`Serializable`].
pub trait Serializer {
    /// Writes bytes from a slice. Should advance value of [`Serializer::tell()`] by [`buf.len`].
    ///
    /// [`buf.len`]: slice::len
    fn write(&mut self, buf: &[u8]);
    /// Current position of the stream. Used by [`CheckedSerialize`].
    ///
    /// [`CheckedSerialize`]: crate::rstd::inlining::CheckedSerialize
    fn tell(&self) -> usize;
}

/// See [`Serializer`].
pub trait Serializable {
    /// Expected to use [`Serializer::write`].
    fn serialize(&self, serializer: &mut dyn Serializer);
}

impl Serializer for Vec<u8> {
    fn write(&mut self, buf: &[u8]) {
        self.extend(buf);
    }

    fn tell(&self) -> usize {
        self.len()
    }
}

/// Trait representing a readable stream used for parsing.
///
/// See [`Serializer`].
pub trait Deserializer {
    /// Read at most `n` bytes.
    fn read_n(&mut self, n: usize) -> &[u8];
    /// Read til the end of the stream.
    fn read_all(&mut self) -> &[u8];
    /// Current position of the stream. Used by [`CheckedParse`].
    ///
    /// [`CheckedParse`]: crate::rstd::inlining::CheckedParse
    fn tell(&self) -> usize;
}

/// Extension trait for [Deserializer]s.
pub trait DeserializerExt: Deserializer {
    /// Try to read exactly `N` bytes.
    fn read_n_const<const N: usize>(&mut self) -> Result<[u8; N], &[u8]> {
        let slice = self.read_n(N);
        match slice.try_into() {
            Ok(array) => Ok(array),
            Err(_) => Err(slice),
        }
    }
}

impl<D: ?Sized + Deserializer> DeserializerExt for D {}