buffered_reader/
eof.rs

1use std::io;
2use std::io::{Error, ErrorKind, Read};
3use std::fmt;
4
5use crate::BufferedReader;
6
7/// Always returns EOF.
8#[derive(Debug)]
9pub struct EOF<C> {
10    cookie: C,
11}
12
13assert_send_and_sync!(EOF<C>
14                      where C: fmt::Debug);
15
16impl<C> fmt::Display for EOF<C> {
17    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18        f.debug_struct("EOF")
19            .finish()
20    }
21}
22
23impl EOF<()> {
24    /// Instantiates a new `EOF`.
25    pub fn new() -> Self {
26        EOF {
27            cookie: (),
28        }
29    }
30}
31
32impl<C> EOF<C> {
33    /// Instantiates a new `EOF` with a cookie.
34    pub fn with_cookie(cookie: C) -> Self {
35        EOF {
36            cookie,
37        }
38    }
39}
40
41impl<C> Read for EOF<C> {
42    fn read(&mut self, _buf: &mut [u8]) -> Result<usize, io::Error> {
43        Ok(0)
44    }
45}
46
47impl<C: fmt::Debug + Sync + Send> BufferedReader<C> for EOF<C> {
48    fn buffer(&self) -> &[u8] {
49        &b""[..]
50    }
51
52    fn data(&mut self, _amount: usize) -> Result<&[u8], io::Error> {
53        Ok(&b""[..])
54    }
55
56    fn consume(&mut self, amount: usize) -> &[u8] {
57        assert_eq!(amount, 0);
58        &b""[..]
59    }
60
61    fn data_consume(&mut self, _amount: usize) -> Result<&[u8], io::Error> {
62        Ok(&b""[..])
63    }
64
65    fn data_consume_hard(&mut self, amount: usize) -> Result<&[u8], io::Error> {
66        if amount == 0 {
67            Ok(&b""[..])
68        } else {
69            Err(Error::new(ErrorKind::UnexpectedEof, "unexpected EOF"))
70        }
71    }
72
73    fn into_inner<'a>(self: Box<Self>) -> Option<Box<dyn BufferedReader<C> + 'a>>
74        where Self: 'a
75    {
76        None
77    }
78
79    fn get_mut(&mut self) -> Option<&mut dyn BufferedReader<C>>
80    {
81        None
82    }
83
84    fn get_ref(&self) -> Option<&dyn BufferedReader<C>>
85    {
86        None
87    }
88
89
90    fn cookie_set(&mut self, cookie: C) -> C {
91        use std::mem;
92
93        mem::replace(&mut self.cookie, cookie)
94    }
95
96    fn cookie_ref(&self) -> &C {
97        &self.cookie
98    }
99
100    fn cookie_mut(&mut self) -> &mut C {
101        &mut self.cookie
102    }
103}
104
105#[cfg(test)]
106mod test {
107    use super::*;
108
109    #[test]
110    fn basics() {
111        let mut reader = EOF::new();
112
113        assert_eq!(reader.buffer(), &b""[..]);
114        assert_eq!(reader.data(100).unwrap(), &b""[..]);
115        assert_eq!(reader.buffer(), &b""[..]);
116        assert_eq!(reader.consume(0), &b""[..]);
117        assert_eq!(reader.data_hard(0).unwrap(), &b""[..]);
118        assert!(reader.data_hard(1).is_err());
119    }
120}