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
use std::io;
use std::fmt;
use std::pin::Pin;

use async_std::stream::Stream;
use async_std::task::{Poll, Context};

use crate::is_transient_error;

/// A stream adapter that logs errors which aren't transient
///
/// See
/// [`ListenExt::log_warnings`](../trait.ListenExt.html#method.log_warnings)
/// for more info.
pub struct LogWarnings<S, F> {
    stream: S,
    logger: F,
}

impl<S: fmt::Debug, F> fmt::Debug for LogWarnings<S, F> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("LogWarnings")
            .field("stream", &self.stream)
            .finish()
    }
}

impl<S: Unpin, F> Unpin for LogWarnings<S, F> {}

impl<S, F> LogWarnings<S, F> {
    pub(crate) fn new(stream: S, f: F) -> LogWarnings<S, F> {
        LogWarnings {
            stream,
            logger: f,
        }
    }

    /// Acquires a reference to the underlying stream that this adapter is
    /// pulling from.
    pub fn get_ref(&self) -> &S {
        &self.stream
    }

    /// Acquires a mutable reference to the underlying stream that this
    /// adapter is pulling from.
    pub fn get_mut(&mut self) -> &mut S {
        &mut self.stream
    }

    /// Consumes this adapter, returning the underlying stream.
    pub fn into_inner(self) -> S {
        self.stream
    }
}

impl<I, S, F> Stream for LogWarnings<S, F>
    where S: Stream<Item=Result<I, io::Error>> + Unpin,
          F: FnMut(&io::Error),
{
    type Item = Result<I, io::Error>;
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context)
        -> Poll<Option<Self::Item>>
    {
        let res = Pin::new(&mut self.stream).poll_next(cx);
        match &res {
            Poll::Ready(Some(Err(e))) if !is_transient_error(e)
            => (self.get_mut().logger)(e),
            _ => {}
        };
        return res;
    }
}