messagepack_core/decode/
nil.rs1use super::{Decode, Error, Result};
4use crate::formats::Format;
5
6pub struct NilDecoder;
8
9impl<'a> Decode<'a> for NilDecoder {
10 type Value = ();
11 fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
12 let (format, buf) = Format::decode(buf)?;
13
14 Self::decode_with_format(format, buf)
15 }
16
17 fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
18 match format {
19 Format::Nil => Ok(((), buf)),
20 _ => Err(Error::UnexpectedFormat),
21 }
22 }
23}
24
25impl<'a> Decode<'a> for () {
26 type Value = ();
27 fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
28 NilDecoder::decode(buf)
29 }
30 fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
31 NilDecoder::decode_with_format(format, buf)
32 }
33}
34
35impl<'a, V> Decode<'a> for Option<V>
36where
37 V: Decode<'a>,
38{
39 type Value = Option<V::Value>;
40 fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
41 let (format, buf) = Format::decode(buf)?;
42 Self::decode_with_format(format, buf)
43 }
44 fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
45 match format {
46 Format::Nil => Ok((None, buf)),
47 other => {
48 let (val, buf) = V::decode_with_format(other, buf)?;
49 Ok((Some(val), buf))
50 }
51 }
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn decode_nil() {
61 let buf: &[u8] = &[0xc0];
62 let (_, rest) = NilDecoder::decode(buf).unwrap();
63 assert_eq!(rest.len(), 0);
64 }
65
66 #[test]
67 fn decode_option() {
68 let buf: &[u8] = &[0xc0];
69 let (decoded, rest) = Option::<bool>::decode(buf).unwrap();
70 assert_eq!(decoded, None);
71 assert_eq!(rest.len(), 0);
72
73 let buf: &[u8] = &[0xc3];
74 let (decoded, rest) = Option::<bool>::decode(buf).unwrap();
75 assert_eq!(decoded, Some(true));
76 assert_eq!(rest.len(), 0);
77 }
78}