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
//! Allow merging async Streams of different output type.
//!
//! It's very similar to Tokio's [`StreamMap`], except that it doesn't require the streams to have the
//! same output type.
//! This can be usefull when you don't know what type of streams should be combined, acting as a
//! runtime dynamic select.
//!
//! # Not a zero-cost-abstraction
//! Since we don't know what types of outputs the streams will generate, the generated output will
//! be a `StreamMapAnyVariant`, a newtype around `Box<dyn Any>`. As a result, we rely on dynamic
//! dispatching to transform it back into the desired output.
//! Benching shows that it's __2x__ as slow as a [`StreamMap`] or a [`select`] macro implementation.
//!
//! [`StreamMap`]: https://docs.rs/tokio/*/tokio/stream/struct.StreamMap.html
//! [`select`]: https://docs.rs/tokio/*/tokio/macro.select.html

use futures::stream::{Stream, StreamExt};
use std::any::Any;
use std::borrow::Borrow;
use std::pin::Pin;
use std::task::{Context, Poll};

/// Combines streams with different output types into one.
pub struct StreamMapAny<K> {
    streams: Vec<(K, BoxedStream)>,
    last_position: usize,
}

/// Newtype around a Boxed Any.
#[derive(Debug)]
pub struct StreamMapAnyVariant(Box<dyn Any>);

struct BoxedStream(Box<dyn Stream<Item = Box<dyn Any>> + Unpin>);

impl<K> StreamMapAny<K> {
    pub const fn new() -> Self {
        Self {
            streams: Vec::new(),
            last_position: 0,
        }
    }

    /// Insert a new stream into the map with a given key.
    ///
    /// If that key is already in use by another stream, that stream will get dropped.
    pub fn insert<S>(&mut self, key: K, stream: S)
    where
        S: Stream + Unpin + 'static,
        S::Item: Any,
        K: Eq,
    {
        let boxed = BoxedStream::new(stream);
        self.streams.push((key, boxed));
    }

    /// Remove a stream from the map with a given key.
    ///
    /// The stream will get dropped.
    pub fn remove<Q>(&mut self, k: &Q)
    where
        K: Borrow<Q>,
        Q: Eq,
    {
        for i in 0..self.streams.len() {
            if self.streams[i].0.borrow() == k {
                self.streams.swap_remove(i);
            }
        }
    }
}

impl<K> StreamMapAny<K>
where
    K: Unpin + Clone,
{
    fn poll_streams(&mut self, cx: &mut Context) -> Poll<Option<(K, StreamMapAnyVariant)>> {
        let start = self.last_position.wrapping_add(1) % self.streams.len();
        let mut idx = start;
        self.last_position = idx;

        for _ in 0..self.streams.len() {
            let (id, stream) = &mut self.streams[idx];

            match Pin::new(stream).poll_next(cx) {
                Poll::Ready(Some(data)) => {
                    return Poll::Ready(Some((id.clone(), StreamMapAnyVariant(data))));
                }
                Poll::Ready(None) => {
                    self.streams.swap_remove(idx);
                    if idx == self.streams.len() {
                        idx = 0;
                    } else if idx < start && start <= self.streams.len() {
                        idx = idx.wrapping_add(1) % self.streams.len();
                    }
                }
                Poll::Pending => {
                    idx = idx.wrapping_add(1) % self.streams.len();
                }
            }
        }

        if self.streams.is_empty() {
            Poll::Ready(None)
        } else {
            Poll::Pending
        }
    }
}

impl<K> Stream for StreamMapAny<K>
where
    K: Unpin + Clone,
{
    type Item = (K, StreamMapAnyVariant);

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        if self.streams.is_empty() {
            return Poll::Ready(None);
        }

        self.poll_streams(cx)
    }
}

impl StreamMapAnyVariant {
    /// Retrieve the value if the type matches T.
    ///
    /// If it doesn't match, the variant will be returned as Err.
    pub fn value<T>(self: Self) -> Result<T, Self>
    where
        T: Any,
    {
        self.0.downcast().map(|v| *v).map_err(Self)
    }

    /// Retrieve a boxed value if the type matches T.
    ///
    /// If it doesn't match, the variant will be returned as Err.
    pub fn boxed_value<T>(self: Self) -> Result<Box<T>, Self>
    where
        T: Any,
    {
        self.0.downcast().map_err(Self)
    }

    /// Retrieve the containing boxed Any.
    pub fn as_boxed_any(self: Self) -> Box<dyn Any> {
        self.0
    }
}

impl BoxedStream {
    fn new<S>(s: S) -> Self
    where
        S: Stream + Unpin + 'static,
        S::Item: Any,
    {
        let stream = s.map(|o| {
            let v: Box<dyn Any> = Box::new(o);
            v
        });
        Self(Box::new(stream))
    }
}

impl Stream for BoxedStream {
    type Item = Box<dyn Any>;
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        Pin::new(&mut *self.0).poll_next(cx)
    }
}