tiny_http/util/
fused_reader.rs

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
use std::io::{IoSliceMut, Read, Result as IoResult};

/// Wraps another reader and provides "fused" behavior.
/// When the underlying reader reaches EOF, it is dropped
/// and the fused reader becomes an empty stub.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FusedReader<R: Read> {
    inner: Option<R>,
}

impl<R: Read> FusedReader<R> {
    pub fn new(inner: R) -> Self {
        Self { inner: Some(inner) }
    }

    #[allow(dead_code)]
    pub fn into_inner(self) -> Option<R> {
        self.inner
    }
}

impl<R: Read> Read for FusedReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        match &mut self.inner {
            Some(r) => {
                let l = r.read(buf)?;
                if l == 0 {
                    self.inner = None;
                }
                Ok(l)
            }
            None => Ok(0),
        }
    }

    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> IoResult<usize> {
        match &mut self.inner {
            Some(r) => {
                let l = r.read_vectored(bufs)?;
                if l == 0 {
                    self.inner = None;
                }
                Ok(l)
            }
            None => Ok(0),
        }
    }
}