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