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
//! Conversion to the `Stream` type from iterators.

use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use crate::dataflow::channels::Message;
use crate::dataflow::operators::generic::operator::source;
use crate::dataflow::operators::CapabilitySet;
use crate::dataflow::{Scope, Stream};
use crate::progress::Timestamp;
use crate::Data;

/// Converts to a timely `Stream`.
pub trait ToStream<T: Timestamp, D: Data> {
    /// Converts to a timely `Stream`.
    ///
    /// # Examples
    ///
    /// ```
    /// use timely::dataflow::operators::{ToStream, Capture};
    /// use timely::dataflow::operators::capture::Extract;
    ///
    /// let (data1, data2) = timely::example(|scope| {
    ///     let data1 = (0..3).to_stream(scope).capture();
    ///     let data2 = vec![0,1,2].to_stream(scope).capture();
    ///     (data1, data2)
    /// });
    ///
    /// assert_eq!(data1.extract(), data2.extract());
    /// ```
    fn to_stream<S: Scope<Timestamp=T>>(self, scope: &mut S) -> Stream<S, D>;
}

impl<T: Timestamp, I: IntoIterator+'static> ToStream<T, I::Item> for I where I::Item: Data {
    fn to_stream<S: Scope<Timestamp=T>>(self, scope: &mut S) -> Stream<S, I::Item> {

        source(scope, "ToStream", |capability, info| {

            // Acquire an activator, so that the operator can rescheduled itself.
            let activator = scope.activator_for(&info.address[..]);

            let mut iterator = self.into_iter().fuse();
            let mut capability = Some(capability);

            move |output| {

                if let Some(element) = iterator.next() {
                    let mut session = output.session(capability.as_ref().unwrap());
                    session.give(element);
                    for element in iterator.by_ref().take((256 * Message::<T, I::Item>::default_length()) - 1) {
                        session.give(element);
                    }
                    activator.activate();
                }
                else {
                    capability = None;
                }
            }
        })
    }
}

/// Data and progress events of the native stream.
pub enum Event<F: IntoIterator, D> {
    /// Indicates that timestamps have advanced to frontier F
    Progress(F),
    /// Indicates that event D happened at time T
    Message(F::Item, D),
}

/// Converts to a timely `Stream`.
pub trait ToStreamAsync<T: Timestamp, D: Data> {
    /// Converts a [native `Stream`](futures_util::stream::Stream) of [`Event`s](Event) into a [timely
    /// `Stream`](crate::dataflow::Stream).
    ///
    /// # Examples
    ///
    /// ```
    /// use futures_util::stream;
    ///
    /// use timely::dataflow::operators::{Capture, Event, ToStream, ToStreamAsync};
    /// use timely::dataflow::operators::capture::Extract;
    ///
    /// let native_stream = stream::iter(vec![
    ///     Event::Message(0, 0),
    ///     Event::Message(0, 1),
    ///     Event::Message(0, 2),
    ///     Event::Progress(Some(0)),
    /// ]);
    ///
    /// let native_stream = Box::pin(native_stream);
    ///
    /// let (data1, data2) = timely::example(|scope| {
    ///     let data1 = native_stream.to_stream(scope).capture();
    ///     let data2 = vec![0,1,2].to_stream(scope).capture();
    ///
    ///     (data1, data2)
    /// });
    ///
    /// assert_eq!(data1.extract(), data2.extract());
    /// ```
    fn to_stream<S: Scope<Timestamp = T>>(self: Pin<Box<Self>>, scope: &S) -> Stream<S, D>;
}

impl<T, D, F, I> ToStreamAsync<T, D> for I
where
    D: Data,
    T: Timestamp,
    F: IntoIterator<Item = T>,
    I: futures_util::stream::Stream<Item = Event<F, D>> + ?Sized + 'static,
{
    fn to_stream<S: Scope<Timestamp = T>>(mut self: Pin<Box<Self>>, scope: &S) -> Stream<S, D> {
        source(scope, "ToStreamAsync", move |capability, info| {
            let activator = Arc::new(scope.sync_activator_for(&info.address[..]));

            let mut cap_set = CapabilitySet::from_elem(capability);

            move |output| {
                let waker = futures_util::task::waker_ref(&activator);
                let mut context = Context::from_waker(&waker);

                // Consume all the ready items of the source_stream and issue them to the operator
                while let Poll::Ready(item) = self.as_mut().poll_next(&mut context) {
                    match item {
                        Some(Event::Progress(time)) => {
                            cap_set.downgrade(time);
                        }
                        Some(Event::Message(time, data)) => {
                            output.session(&cap_set.delayed(&time)).give(data);
                        }
                        None => {
                            cap_set.downgrade(&[]);
                            break;
                        }
                    }
                }
            }
        })
    }
}