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
//! [`Plain`] type for storing raw byte sequnces.

use std::convert::Infallible;

use super::*;

/// Raw bytes storage. Use [`Plain::raw`] to get the data.
///
/// Note: this type uses [`Deserializer::read_all`] for parsing.
#[derive(Clone, Debug)]
pub struct Plain {
    data: Vec<u8>,
}

impl Serializable for Plain {
    fn serialize(&self, serializer: &mut dyn Serializer) {
        serializer.write(&self.data)
    }
}

impl AtomicBase for Plain {
    type AParseError = Infallible;
}

impl ImplMode for Plain {
    type Mode = RegularMode;
}

impl CRegularAtomic for Plain {
    fn cra_deserialize(stream: impl Stream) -> AParseResult<Self> {
        Ok(stream.iread_all(Plain::from_slice))
    }

    fn cra_extend(mut self, tail: &[u8]) -> AParseResult<Self> {
        self.data.extend_from_slice(tail);
        Ok(self)
    }
}

impl Plain {
    /// Copy bytes into a new instance.
    pub fn from_slice(slice: &[u8]) -> Self {
        Plain { data: slice.into() }
    }

    /// Copy of bytes stored inside.
    pub fn raw(&self) -> Vec<u8> {
        self.data.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rstd::*;

    #[test]
    fn can_parse_plain_slice() {
        let plain = Plain::parse_slice(b"slice").unwrap();
        assert_eq!(plain.bytes().as_slice(), b"slice");
    }
}