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