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
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use dfb::*;

use super::{AnySender, AnyRecvError};
use core::any::*;
use std::sync::mpsc::{self, Receiver};

/// An [mpsc::channel] that supports dynamic typing and contains a buffer to 
/// prevent the need for dynamic types to be exposed. 
pub fn buffered_channel() -> (AnySender, BufferedReceiver)
{
    let (tx, rx) = mpsc::channel();
    (AnySender(tx), BufferedReceiver { rx, buf: Dfb::new() })
}

/// Wraps an [mpsc::Receiver] to support dynamic typing and buffered results.
#[derive(Debug)]
pub struct BufferedReceiver
{
    pub rx: Receiver<Box<dyn Any>>,
    pub buf: Dfb
}
unsafe impl Send for BufferedReceiver {}

impl BufferedReceiver
{
    /// Wraps [mpsc::Receiver::recv]. See [BufRecvError] for details on the 
    /// return value. Will continuously recv until the supplied type is found. 
    /// Any unmatching types received will be placed in the buffer.
    pub fn recv_until<T: 'static>(&mut self) -> Result<T, AnyRecvError>
    {
        loop
        {
            match self.recv::<T>()
            {
                Err(err) => match err
                {
                    AnyRecvError::BufRecvError(_type_id) => continue,
                    err => break Err(err),
                },
                ok => break ok
            }
        }
    }

    /// Wraps [mpsc::Receiver::recv]. See [BufRecvError] for details on the 
    /// return value. Will attempt to take from the internal buffer before
    /// performing an actual channel recv.
    pub fn recv<T: 'static>(&mut self) -> Result<T, AnyRecvError>
    {
        match self.buf.remove::<T>()
        {
            Some(t) => Ok(t),
            None => self.rx
                .recv()
                .map_err(AnyRecvError::RecvError)
                .and_then(|r| match r.downcast()
                {
                    Ok(r) => Ok(*r),
                    Err(r) => 
                    {
                        let err = Err(AnyRecvError::BufRecvError(r.as_ref().type_id()));
                        self.buf.insert_dyn(r);
                        err
                    },
                })
        }
    }

    /// Wraps [mpsc::Receiver::recv]. See [BufRecvError] for details on the 
    /// return value. Will perform a channel recv regardless of whether or not
    /// anything is contained in the buffer.
    pub fn recv_live<T: 'static>(&mut self) -> Result<T, AnyRecvError>
    {
        self.rx
            .recv()
            .map_err(AnyRecvError::RecvError)
            .and_then(|r| match r.downcast()
            {
                Ok(r) => Ok(*r),
                Err(r) => 
                {
                    let err = Err(AnyRecvError::BufRecvError(r.as_ref().type_id()));
                    self.buf.insert_dyn(r);
                    err
                },
            })
    }

    /// Wraps [mpsc::Receiver::recv_timeout]. See [BufRecvError] for 
    /// details on the return value. Will attempt to take from the internal 
    /// buffer before performing an actual channel recv_timeout.
    pub fn recv_timeout<T: 'static>(&mut self, timeout: std::time::Duration) -> Result<T, AnyRecvError>
    {
        match self.buf.remove::<T>()
        {
            Some(t) => Ok(t),
            None => self.rx
                .recv_timeout(timeout)
                .map_err(AnyRecvError::RecvTimeoutError)
                .and_then(|r| match r.downcast()
                {
                    Ok(r) => Ok(*r),
                    Err(r) => 
                    {
                        let err = Err(AnyRecvError::BufRecvError(r.as_ref().type_id()));
                        self.buf.insert_dyn(r);
                        err
                    }
                })
        }
    }

    /// Wraps [mpsc::Receiver::recv_timeout]. See [BufRecvError] for 
    /// details on the return value. Will perform a channel recv_timeout 
    /// regardless of whether or not anything is contained in the buffer.
    pub fn recv_timeout_live<T: 'static>(&mut self, timeout: std::time::Duration) -> Result<T, AnyRecvError>
    {
        match self.buf.remove::<T>()
        {
            Some(t) => Ok(t),
            None => self.rx
                .recv_timeout(timeout)
                .map_err(AnyRecvError::RecvTimeoutError)
                .and_then(|r| match r.downcast()
                {
                    Ok(r) => Ok(*r),
                    Err(r) => 
                    {
                        let err = Err(AnyRecvError::BufRecvError(r.as_ref().type_id()));
                        self.buf.insert_dyn(r);
                        err
                    }
                })
        }
    }

    /// Wraps [mpsc::Receiver::try_recv]. See [BufRecvError] for 
    /// details on the return value. Will attempt to take from the internal 
    /// buffer before performing an actual channel recv_timeout.
    pub fn try_recv<T: 'static>(&mut self) -> Result<T, AnyRecvError>
    {
        match self.buf.remove::<T>()
        {
            Some(t) => Ok(t),
            None => self.rx
                .try_recv()
                .map_err(AnyRecvError::TryRecvError)
                .and_then(|r| match r.downcast()
                {
                    Ok(r) => Ok(*r),
                    Err(r) => 
                    {
                        let err = Err(AnyRecvError::BufRecvError(r.as_ref().type_id()));
                        self.buf.insert_dyn(r);
                        err
                    }
                })
        }
    }

    /// Wraps [mpsc::Receiver::try_recv]. See [BufRecvError] for 
    /// details on the return value. Will perform a channel recv_timeout 
    /// regardless of whether or not anything is contained in the buffer.
    pub fn try_recv_live<T: 'static>(&mut self) -> Result<T, AnyRecvError>
    {
        match self.buf.remove::<T>()
        {
            Some(t) => Ok(t),
            None => self.rx
                .try_recv()
                .map_err(AnyRecvError::TryRecvError)
                .and_then(|r| match r.downcast()
                {
                    Ok(r) => Ok(*r),
                    Err(r) => 
                    {
                        let err = Err(AnyRecvError::BufRecvError(r.as_ref().type_id()));
                        self.buf.insert_dyn(r);
                        err
                    }
                })
        }
    }

    /// Wraps [mpsc::Receiver::recv]. See [crate::AnyRecvError] for details on the 
    /// return value. Bypasses the buffer entirely.
    pub fn recv_nobuf<T: 'static>(&self) -> Result<T, AnyRecvError>
    {
        self.rx
            .recv()
            .map_err(AnyRecvError::RecvError)
            .and_then(|r| match r.downcast()
            {
                Ok(r) => Ok(*r),
                Err(r) => Err(AnyRecvError::WrongType(r)),
            })
    }

    /// Wraps [mpsc::Receiver::recv_timeout]. See [crate::AnyRecvError] for 
    /// details on the return value. Bypasses the buffer entirely.
    pub fn recv_timeout_nobuf<T: 'static>(&self, timeout: std::time::Duration) -> Result<T, AnyRecvError>
    {
        self.rx
            .recv_timeout(timeout)
            .map_err(AnyRecvError::RecvTimeoutError)
            .and_then(|r| match r.downcast()
            {
                Ok(r) => Ok(*r),
                Err(r) => Err(AnyRecvError::WrongType(r)),
            })
    }

    /// Wraps [mpsc::Receiver::try_recv]. See [crate::AnyRecvError] for 
    /// details on the return value. Bypasses the buffer entirely.
    pub fn try_recv_nobuf<T: 'static>(&self) -> Result<T, AnyRecvError>
    {
        self.rx
            .try_recv()
            .map_err(AnyRecvError::TryRecvError)
            .and_then(|r| match r.downcast()
            {
                Ok(r) => Ok(*r),
                Err(r) => Err(AnyRecvError::WrongType(r)),
            })
    }

    /// Will attempt to read a value from the internal buffer. Will not do a
    /// channel recv of any kind even if the buffer is empty.
    pub fn recv_buf<T: 'static>(&mut self) -> Result<T, AnyRecvError>
    {
        match self.buf.remove::<T>()
        {
            Some(t) => Ok(t),
            None => Err(AnyRecvError::EmptyBuffer)
        }
    }
}