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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use {ByteCount, Decode, Eos, ErrorKind, Result};
#[derive(Debug)]
pub struct DecodedValue<T>(Option<T>);
impl<T> DecodedValue<T> {
pub fn new(value: T) -> Self {
DecodedValue(Some(value))
}
}
impl<T> Decode for DecodedValue<T> {
type Item = T;
fn decode(&mut self, _buf: &[u8], _eos: Eos) -> Result<(usize, Option<Self::Item>)> {
let item = track_assert_some!(self.0.take(), ErrorKind::DecoderTerminated);
Ok((0, Some(item)))
}
fn requiring_bytes(&self) -> ByteCount {
ByteCount::Finite(0)
}
}
#[derive(Debug, Default)]
pub struct NullDecoder;
impl Decode for NullDecoder {
type Item = ();
fn decode(&mut self, _buf: &[u8], _eos: Eos) -> Result<(usize, Option<Self::Item>)> {
Ok((0, Some(())))
}
fn requiring_bytes(&self) -> ByteCount {
ByteCount::Finite(0)
}
}
#[cfg(test)]
mod test {
use super::*;
use {Decode, Eos, ErrorKind};
#[test]
fn decoded_value_works() {
let mut decoder = DecodedValue::new(3);
assert_eq!(
decoder.decode(&[][..], Eos::new(false)).unwrap(),
(0, Some(3))
);
assert_eq!(
decoder
.decode(&[][..], Eos::new(false))
.err()
.map(|e| *e.kind()),
Some(ErrorKind::DecoderTerminated)
);
}
#[test]
fn null_decoder_works() {
let mut decoder = NullDecoder;
assert_eq!(
decoder.decode(&[][..], Eos::new(false)).unwrap(),
(0, Some(()))
);
assert_eq!(
decoder.decode(&[][..], Eos::new(false)).unwrap(),
(0, Some(()))
);
}
}