differential_dataflow/
collection.rs

1//! Types and traits associated with collections of data.
2//!
3//! The `Collection` type is differential dataflow's core abstraction for an updatable pile of data.
4//!
5//! Most differential dataflow programs are "collection-oriented", in the sense that they transform
6//! one collection into another, using operators defined on collections. This contrasts with a more
7//! imperative programming style, in which one might iterate through the contents of a collection
8//! manually. The higher-level of programming allows differential dataflow to provide efficient
9//! implementations, and to support efficient incremental updates to the collections.
10
11use std::hash::Hash;
12
13use timely::Container;
14use timely::Data;
15use timely::progress::Timestamp;
16use timely::order::Product;
17use timely::dataflow::scopes::{Child, child::Iterative};
18use timely::dataflow::Scope;
19use timely::dataflow::operators::*;
20use timely::dataflow::StreamCore;
21
22use crate::difference::{Semigroup, Abelian, Multiply};
23use crate::lattice::Lattice;
24use crate::hashable::Hashable;
25
26/// A mutable collection of values of type `D`
27///
28/// The `Collection` type is the core abstraction in differential dataflow programs. As you write your
29/// differential dataflow computation, you write as if the collection is a static dataset to which you
30/// apply functional transformations, creating new collections. Once your computation is written, you
31/// are able to mutate the collection (by inserting and removing elements); differential dataflow will
32/// propagate changes through your functional computation and report the corresponding changes to the
33/// output collections.
34///
35/// Each collection has three generic parameters. The parameter `G` is for the scope in which the
36/// collection exists; as you write more complicated programs you may wish to introduce nested scopes
37/// (e.g. for iteration) and this parameter tracks the scope (for timely dataflow's benefit). The `D`
38/// parameter is the type of data in your collection, for example `String`, or `(u32, Vec<Option<()>>)`.
39/// The `R` parameter represents the types of changes that the data undergo, and is most commonly (and
40/// defaults to) `isize`, representing changes to the occurrence count of each record.
41#[derive(Clone)]
42pub struct Collection<G: Scope, D, R = isize, C = Vec<(D, <G as ScopeParent>::Timestamp, R)>> {
43    /// The underlying timely dataflow stream.
44    ///
45    /// This field is exposed to support direct timely dataflow manipulation when required, but it is
46    /// not intended to be the idiomatic way to work with the collection.
47    ///
48    /// The timestamp in the data is required to always be at least the timestamp _of_ the data, in
49    /// the timely-dataflow sense. If this invariant is not upheld, differential operators may behave
50    /// unexpectedly.
51    pub inner: timely::dataflow::StreamCore<G, C>,
52    /// Phantom data for unreferenced `D` and `R` types.
53    phantom: std::marker::PhantomData<(D, R)>,
54}
55
56impl<G: Scope, D, R, C> Collection<G, D, R, C> {
57    /// Creates a new Collection from a timely dataflow stream.
58    ///
59    /// This method seems to be rarely used, with the `as_collection` method on streams being a more
60    /// idiomatic approach to convert timely streams to collections. Also, the `input::Input` trait
61    /// provides a `new_collection` method which will create a new collection for you without exposing
62    /// the underlying timely stream at all.
63    ///
64    /// This stream should satisfy the timestamp invariant as documented on [Collection]; this
65    /// method does not check it.
66    pub fn new(stream: StreamCore<G, C>) -> Collection<G, D, R, C> {
67        Collection { inner: stream, phantom: std::marker::PhantomData }
68    }
69}
70impl<G: Scope, D, R, C: Container + Clone + 'static> Collection<G, D, R, C> {
71    /// Creates a new collection accumulating the contents of the two collections.
72    ///
73    /// Despite the name, differential dataflow collections are unordered. This method is so named because the
74    /// implementation is the concatenation of the stream of updates, but it corresponds to the addition of the
75    /// two collections.
76    ///
77    /// # Examples
78    ///
79    /// ```
80    /// use differential_dataflow::input::Input;
81    ///
82    /// ::timely::example(|scope| {
83    ///
84    ///     let data = scope.new_collection_from(1 .. 10).1;
85    ///
86    ///     let odds = data.filter(|x| x % 2 == 1);
87    ///     let evens = data.filter(|x| x % 2 == 0);
88    ///
89    ///     odds.concat(&evens)
90    ///         .assert_eq(&data);
91    /// });
92    /// ```
93    pub fn concat(&self, other: &Self) -> Self {
94        self.inner
95            .concat(&other.inner)
96            .as_collection()
97    }
98    /// Creates a new collection accumulating the contents of the two collections.
99    ///
100    /// Despite the name, differential dataflow collections are unordered. This method is so named because the
101    /// implementation is the concatenation of the stream of updates, but it corresponds to the addition of the
102    /// two collections.
103    ///
104    /// # Examples
105    ///
106    /// ```
107    /// use differential_dataflow::input::Input;
108    ///
109    /// ::timely::example(|scope| {
110    ///
111    ///     let data = scope.new_collection_from(1 .. 10).1;
112    ///
113    ///     let odds = data.filter(|x| x % 2 == 1);
114    ///     let evens = data.filter(|x| x % 2 == 0);
115    ///
116    ///     odds.concatenate(Some(evens))
117    ///         .assert_eq(&data);
118    /// });
119    /// ```
120    pub fn concatenate<I>(&self, sources: I) -> Self
121    where
122        I: IntoIterator<Item=Self>
123    {
124        self.inner
125            .concatenate(sources.into_iter().map(|x| x.inner))
126            .as_collection()
127    }
128    // Brings a Collection into a nested region.
129    ///
130    /// This method is a specialization of `enter` to the case where the nested scope is a region.
131    /// It removes the need for an operator that adjusts the timestamp.
132    pub fn enter_region<'a>(&self, child: &Child<'a, G, <G as ScopeParent>::Timestamp>) -> Collection<Child<'a, G, <G as ScopeParent>::Timestamp>, D, R, C> {
133        self.inner
134            .enter(child)
135            .as_collection()
136    }
137    /// Applies a supplied function to each batch of updates.
138    ///
139    /// This method is analogous to `inspect`, but operates on batches and reveals the timestamp of the
140    /// timely dataflow capability associated with the batch of updates. The observed batching depends
141    /// on how the system executes, and may vary run to run.
142    ///
143    /// # Examples
144    ///
145    /// ```
146    /// use differential_dataflow::input::Input;
147    ///
148    /// ::timely::example(|scope| {
149    ///     scope.new_collection_from(1 .. 10).1
150    ///          .map_in_place(|x| *x *= 2)
151    ///          .filter(|x| x % 2 == 1)
152    ///          .inspect_container(|event| println!("event: {:?}", event));
153    /// });
154    /// ```
155    pub fn inspect_container<F>(&self, func: F) -> Self
156    where F: FnMut(Result<(&G::Timestamp, &C), &[G::Timestamp]>)+'static {
157        self.inner
158            .inspect_container(func)
159            .as_collection()
160    }
161    /// Attaches a timely dataflow probe to the output of a Collection.
162    ///
163    /// This probe is used to determine when the state of the Collection has stabilized and can
164    /// be read out.
165    pub fn probe(&self) -> probe::Handle<G::Timestamp> {
166        self.inner
167            .probe()
168    }
169    /// Attaches a timely dataflow probe to the output of a Collection.
170    ///
171    /// This probe is used to determine when the state of the Collection has stabilized and all updates observed.
172    /// In addition, a probe is also often use to limit the number of rounds of input in flight at any moment; a
173    /// computation can wait until the probe has caught up to the input before introducing more rounds of data, to
174    /// avoid swamping the system.
175    pub fn probe_with(&self, handle: &probe::Handle<G::Timestamp>) -> Self {
176        Self::new(self.inner.probe_with(handle))
177    }
178    /// The scope containing the underlying timely dataflow stream.
179    pub fn scope(&self) -> G {
180        self.inner.scope()
181    }
182
183    /// Creates a new collection whose counts are the negation of those in the input.
184    ///
185    /// This method is most commonly used with `concat` to get those element in one collection but not another.
186    /// However, differential dataflow computations are still defined for all values of the difference type `R`,
187    /// including negative counts.
188    ///
189    /// # Examples
190    ///
191    /// ```
192    /// use differential_dataflow::input::Input;
193    ///
194    /// ::timely::example(|scope| {
195    ///
196    ///     let data = scope.new_collection_from(1 .. 10).1;
197    ///
198    ///     let odds = data.filter(|x| x % 2 == 1);
199    ///     let evens = data.filter(|x| x % 2 == 0);
200    ///
201    ///     odds.negate()
202    ///         .concat(&data)
203    ///         .assert_eq(&evens);
204    /// });
205    /// ```
206    // TODO: Removing this function is possible, but breaks existing callers of `negate` who expect
207    //       an inherent method on `Collection`.
208    pub fn negate(&self) -> Collection<G, D, R, C> where StreamCore<G, C>: crate::operators::Negate<G, C> {
209        crate::operators::Negate::negate(&self.inner).as_collection()
210    }
211}
212
213impl<G: Scope, D: Clone+'static, R: Clone+'static> Collection<G, D, R> {
214    /// Creates a new collection by applying the supplied function to each input element.
215    ///
216    /// # Examples
217    ///
218    /// ```
219    /// use differential_dataflow::input::Input;
220    ///
221    /// ::timely::example(|scope| {
222    ///     scope.new_collection_from(1 .. 10).1
223    ///          .map(|x| x * 2)
224    ///          .filter(|x| x % 2 == 1)
225    ///          .assert_empty();
226    /// });
227    /// ```
228    pub fn map<D2, L>(&self, mut logic: L) -> Collection<G, D2, R>
229    where D2: Data,
230          L: FnMut(D) -> D2 + 'static
231    {
232        self.inner
233            .map(move |(data, time, delta)| (logic(data), time, delta))
234            .as_collection()
235    }
236    /// Creates a new collection by applying the supplied function to each input element.
237    ///
238    /// Although the name suggests in-place mutation, this function does not change the source collection,
239    /// but rather re-uses the underlying allocations in its implementation. The method is semantically
240    /// equivalent to `map`, but can be more efficient.
241    ///
242    /// # Examples
243    ///
244    /// ```
245    /// use differential_dataflow::input::Input;
246    ///
247    /// ::timely::example(|scope| {
248    ///     scope.new_collection_from(1 .. 10).1
249    ///          .map_in_place(|x| *x *= 2)
250    ///          .filter(|x| x % 2 == 1)
251    ///          .assert_empty();
252    /// });
253    /// ```
254    pub fn map_in_place<L>(&self, mut logic: L) -> Collection<G, D, R>
255    where L: FnMut(&mut D) + 'static {
256        self.inner
257            .map_in_place(move |&mut (ref mut data, _, _)| logic(data))
258            .as_collection()
259    }
260    /// Creates a new collection by applying the supplied function to each input element and accumulating the results.
261    ///
262    /// This method extracts an iterator from each input element, and extracts the full contents of the iterator. Be
263    /// warned that if the iterators produce substantial amounts of data, they are currently fully drained before
264    /// attempting to consolidate the results.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// use differential_dataflow::input::Input;
270    ///
271    /// ::timely::example(|scope| {
272    ///     scope.new_collection_from(1 .. 10).1
273    ///          .flat_map(|x| 0 .. x);
274    /// });
275    /// ```
276    pub fn flat_map<I, L>(&self, mut logic: L) -> Collection<G, I::Item, R>
277        where G::Timestamp: Clone,
278              I: IntoIterator,
279              I::Item: Data,
280              L: FnMut(D) -> I + 'static {
281        self.inner
282            .flat_map(move |(data, time, delta)| logic(data).into_iter().map(move |x| (x, time.clone(), delta.clone())))
283            .as_collection()
284    }
285    /// Creates a new collection containing those input records satisfying the supplied predicate.
286    ///
287    /// # Examples
288    ///
289    /// ```
290    /// use differential_dataflow::input::Input;
291    ///
292    /// ::timely::example(|scope| {
293    ///     scope.new_collection_from(1 .. 10).1
294    ///          .map(|x| x * 2)
295    ///          .filter(|x| x % 2 == 1)
296    ///          .assert_empty();
297    /// });
298    /// ```
299    pub fn filter<L>(&self, mut logic: L) -> Collection<G, D, R>
300    where L: FnMut(&D) -> bool + 'static {
301        self.inner
302            .filter(move |(data, _, _)| logic(data))
303            .as_collection()
304    }
305    /// Replaces each record with another, with a new difference type.
306    ///
307    /// This method is most commonly used to take records containing aggregatable data (e.g. numbers to be summed)
308    /// and move the data into the difference component. This will allow differential dataflow to update in-place.
309    ///
310    /// # Examples
311    ///
312    /// ```
313    /// use differential_dataflow::input::Input;
314    ///
315    /// ::timely::example(|scope| {
316    ///
317    ///     let nums = scope.new_collection_from(0 .. 10).1;
318    ///     let x1 = nums.flat_map(|x| 0 .. x);
319    ///     let x2 = nums.map(|x| (x, 9 - x))
320    ///                  .explode(|(x,y)| Some((x,y)));
321    ///
322    ///     x1.assert_eq(&x2);
323    /// });
324    /// ```
325    pub fn explode<D2, R2, I, L>(&self, mut logic: L) -> Collection<G, D2, <R2 as Multiply<R>>::Output>
326    where D2: Data,
327          R2: Semigroup+Multiply<R>,
328          <R2 as Multiply<R>>::Output: Semigroup+'static,
329          I: IntoIterator<Item=(D2,R2)>,
330          L: FnMut(D)->I+'static,
331    {
332        self.inner
333            .flat_map(move |(x, t, d)| logic(x).into_iter().map(move |(x,d2)| (x, t.clone(), d2.multiply(&d))))
334            .as_collection()
335    }
336
337    /// Joins each record against a collection defined by the function `logic`.
338    ///
339    /// This method performs what is essentially a join with the collection of records `(x, logic(x))`.
340    /// Rather than materialize this second relation, `logic` is applied to each record and the appropriate
341    /// modifications made to the results, namely joining timestamps and multiplying differences.
342    ///
343    /// #Examples
344    ///
345    /// ```
346    /// use differential_dataflow::input::Input;
347    ///
348    /// ::timely::example(|scope| {
349    ///     // creates `x` copies of `2*x` from time `3*x` until `4*x`,
350    ///     // for x from 0 through 9.
351    ///     scope.new_collection_from(0 .. 10isize).1
352    ///          .join_function(|x|
353    ///              //   data      time      diff
354    ///              vec![(2*x, (3*x) as u64,  x),
355    ///                   (2*x, (4*x) as u64, -x)]
356    ///           );
357    /// });
358    /// ```
359    pub fn join_function<D2, R2, I, L>(&self, mut logic: L) -> Collection<G, D2, <R2 as Multiply<R>>::Output>
360    where G::Timestamp: Lattice,
361          D2: Data,
362          R2: Semigroup+Multiply<R>,
363          <R2 as Multiply<R>>::Output: Semigroup+'static,
364          I: IntoIterator<Item=(D2,G::Timestamp,R2)>,
365          L: FnMut(D)->I+'static,
366    {
367        self.inner
368            .flat_map(move |(x, t, d)| logic(x).into_iter().map(move |(x,t2,d2)| (x, t.join(&t2), d2.multiply(&d))))
369            .as_collection()
370    }
371
372    /// Brings a Collection into a nested scope.
373    ///
374    /// # Examples
375    ///
376    /// ```
377    /// use timely::dataflow::Scope;
378    /// use differential_dataflow::input::Input;
379    ///
380    /// ::timely::example(|scope| {
381    ///
382    ///     let data = scope.new_collection_from(1 .. 10).1;
383    ///
384    ///     let result = scope.region(|child| {
385    ///         data.enter(child)
386    ///             .leave()
387    ///     });
388    ///
389    ///     data.assert_eq(&result);
390    /// });
391    /// ```
392    pub fn enter<'a, T>(&self, child: &Child<'a, G, T>) -> Collection<Child<'a, G, T>, D, R>
393    where
394        T: Refines<<G as ScopeParent>::Timestamp>,
395    {
396        self.inner
397            .enter(child)
398            .map(|(data, time, diff)| (data, T::to_inner(time), diff))
399            .as_collection()
400    }
401
402    /// Brings a Collection into a nested scope, at varying times.
403    ///
404    /// The `initial` function indicates the time at which each element of the Collection should appear.
405    ///
406    /// # Examples
407    ///
408    /// ```
409    /// use timely::dataflow::Scope;
410    /// use differential_dataflow::input::Input;
411    ///
412    /// ::timely::example(|scope| {
413    ///
414    ///     let data = scope.new_collection_from(1 .. 10).1;
415    ///
416    ///     let result = scope.iterative::<u64,_,_>(|child| {
417    ///         data.enter_at(child, |x| *x)
418    ///             .leave()
419    ///     });
420    ///
421    ///     data.assert_eq(&result);
422    /// });
423    /// ```
424    pub fn enter_at<'a, T, F>(&self, child: &Iterative<'a, G, T>, mut initial: F) -> Collection<Iterative<'a, G, T>, D, R>
425    where
426        T: Timestamp+Hash,
427        F: FnMut(&D) -> T + Clone + 'static,
428        G::Timestamp: Hash,
429    {
430        self.inner
431            .enter(child)
432            .map(move |(data, time, diff)| {
433                let new_time = Product::new(time, initial(&data));
434                (data, new_time, diff)
435            })
436            .as_collection()
437    }
438
439    /// Delays each difference by a supplied function.
440    ///
441    /// It is assumed that `func` only advances timestamps; this is not verified, and things may go horribly
442    /// wrong if that assumption is incorrect. It is also critical that `func` be monotonic: if two times are
443    /// ordered, they should have the same order or compare equal once `func` is applied to them (this
444    /// is because we advance the timely capability with the same logic, and it must remain `less_equal`
445    /// to all of the data timestamps).
446    pub fn delay<F>(&self, func: F) -> Collection<G, D, R>
447    where F: FnMut(&G::Timestamp) -> G::Timestamp + Clone + 'static {
448
449        let mut func1 = func.clone();
450        let mut func2 = func.clone();
451
452        self.inner
453            .delay_batch(move |x| func1(x))
454            .map_in_place(move |x| x.1 = func2(&x.1))
455            .as_collection()
456    }
457
458    /// Applies a supplied function to each update.
459    ///
460    /// This method is most commonly used to report information back to the user, often for debugging purposes.
461    /// Any function can be used here, but be warned that the incremental nature of differential dataflow does
462    /// not guarantee that it will be called as many times as you might expect.
463    ///
464    /// The `(data, time, diff)` triples indicate a change `diff` to the frequency of `data` which takes effect
465    /// at the logical time `time`. When times are totally ordered (for example, `usize`), these updates reflect
466    /// the changes along the sequence of collections. For partially ordered times, the mathematics are more
467    /// interesting and less intuitive, unfortunately.
468    ///
469    /// # Examples
470    ///
471    /// ```
472    /// use differential_dataflow::input::Input;
473    ///
474    /// ::timely::example(|scope| {
475    ///     scope.new_collection_from(1 .. 10).1
476    ///          .map_in_place(|x| *x *= 2)
477    ///          .filter(|x| x % 2 == 1)
478    ///          .inspect(|x| println!("error: {:?}", x));
479    /// });
480    /// ```
481    pub fn inspect<F>(&self, func: F) -> Collection<G, D, R>
482    where F: FnMut(&(D, G::Timestamp, R))+'static {
483        self.inner
484            .inspect(func)
485            .as_collection()
486    }
487    /// Applies a supplied function to each batch of updates.
488    ///
489    /// This method is analogous to `inspect`, but operates on batches and reveals the timestamp of the
490    /// timely dataflow capability associated with the batch of updates. The observed batching depends
491    /// on how the system executes, and may vary run to run.
492    ///
493    /// # Examples
494    ///
495    /// ```
496    /// use differential_dataflow::input::Input;
497    ///
498    /// ::timely::example(|scope| {
499    ///     scope.new_collection_from(1 .. 10).1
500    ///          .map_in_place(|x| *x *= 2)
501    ///          .filter(|x| x % 2 == 1)
502    ///          .inspect_batch(|t,xs| println!("errors @ {:?}: {:?}", t, xs));
503    /// });
504    /// ```
505    pub fn inspect_batch<F>(&self, mut func: F) -> Collection<G, D, R>
506    where F: FnMut(&G::Timestamp, &[(D, G::Timestamp, R)])+'static {
507        self.inner
508            .inspect_batch(move |time, data| func(time, data))
509            .as_collection()
510    }
511
512    /// Assert if the collection is ever non-empty.
513    ///
514    /// Because this is a dataflow fragment, the test is only applied as the computation is run. If the computation
515    /// is not run, or not run to completion, there may be un-exercised times at which the collection could be
516    /// non-empty. Typically, a timely dataflow computation runs to completion on drop, and so clean exit from a
517    /// program should indicate that this assertion never found cause to complain.
518    ///
519    /// # Examples
520    ///
521    /// ```
522    /// use differential_dataflow::input::Input;
523    ///
524    /// ::timely::example(|scope| {
525    ///     scope.new_collection_from(1 .. 10).1
526    ///          .map(|x| x * 2)
527    ///          .filter(|x| x % 2 == 1)
528    ///          .assert_empty();
529    /// });
530    /// ```
531    pub fn assert_empty(&self)
532    where D: crate::ExchangeData+Hashable,
533          R: crate::ExchangeData+Hashable + Semigroup,
534          G::Timestamp: Lattice+Ord,
535    {
536        self.consolidate()
537            .inspect(|x| panic!("Assertion failed: non-empty collection: {:?}", x));
538    }
539}
540
541use timely::dataflow::scopes::ScopeParent;
542use timely::progress::timestamp::Refines;
543
544/// Methods requiring a nested scope.
545impl<'a, G: Scope, T: Timestamp, D: Clone+'static, R: Clone+'static> Collection<Child<'a, G, T>, D, R>
546where
547    T: Refines<<G as ScopeParent>::Timestamp>,
548{
549    /// Returns the final value of a Collection from a nested scope to its containing scope.
550    ///
551    /// # Examples
552    ///
553    /// ```
554    /// use timely::dataflow::Scope;
555    /// use differential_dataflow::input::Input;
556    ///
557    /// ::timely::example(|scope| {
558    ///
559    ///    let data = scope.new_collection_from(1 .. 10).1;
560    ///
561    ///    let result = scope.region(|child| {
562    ///         data.enter(child)
563    ///             .leave()
564    ///     });
565    ///
566    ///     data.assert_eq(&result);
567    /// });
568    /// ```
569    pub fn leave(&self) -> Collection<G, D, R> {
570        self.inner
571            .leave()
572            .map(|(data, time, diff)| (data, time.to_outer(), diff))
573            .as_collection()
574    }
575}
576
577/// Methods requiring a region as the scope.
578impl<G: Scope, D, R, C: Container+Data> Collection<Child<'_, G, G::Timestamp>, D, R, C>
579{
580    /// Returns the value of a Collection from a nested region to its containing scope.
581    ///
582    /// This method is a specialization of `leave` to the case that of a nested region.
583    /// It removes the need for an operator that adjusts the timestamp.
584    pub fn leave_region(&self) -> Collection<G, D, R, C> {
585        self.inner
586            .leave()
587            .as_collection()
588    }
589}
590
591/// Methods requiring an Abelian difference, to support negation.
592impl<G: Scope, D: Clone+'static, R: Abelian+'static> Collection<G, D, R> where G::Timestamp: Data {
593    /// Assert if the collections are ever different.
594    ///
595    /// Because this is a dataflow fragment, the test is only applied as the computation is run. If the computation
596    /// is not run, or not run to completion, there may be un-exercised times at which the collections could vary.
597    /// Typically, a timely dataflow computation runs to completion on drop, and so clean exit from a program should
598    /// indicate that this assertion never found cause to complain.
599    ///
600    /// # Examples
601    ///
602    /// ```
603    /// use differential_dataflow::input::Input;
604    ///
605    /// ::timely::example(|scope| {
606    ///
607    ///     let data = scope.new_collection_from(1 .. 10).1;
608    ///
609    ///     let odds = data.filter(|x| x % 2 == 1);
610    ///     let evens = data.filter(|x| x % 2 == 0);
611    ///
612    ///     odds.concat(&evens)
613    ///         .assert_eq(&data);
614    /// });
615    /// ```
616    pub fn assert_eq(&self, other: &Self)
617    where D: crate::ExchangeData+Hashable,
618          R: crate::ExchangeData+Hashable,
619          G::Timestamp: Lattice+Ord
620    {
621        self.negate()
622            .concat(other)
623            .assert_empty();
624    }
625}
626
627/// Conversion to a differential dataflow Collection.
628pub trait AsCollection<G: Scope, D, R, C> {
629    /// Converts the type to a differential dataflow collection.
630    fn as_collection(&self) -> Collection<G, D, R, C>;
631}
632
633impl<G: Scope, D, R, C: Clone> AsCollection<G, D, R, C> for StreamCore<G, C> {
634    /// Converts the type to a differential dataflow collection.
635    ///
636    /// By calling this method, you guarantee that the timestamp invariant (as documented on
637    /// [Collection]) is upheld. This method will not check it.
638    fn as_collection(&self) -> Collection<G, D, R, C> {
639        Collection::<G,D,R,C>::new(self.clone())
640    }
641}
642
643/// Concatenates multiple collections.
644///
645/// This method has the effect of a sequence of calls to `concat`, but it does
646/// so in one operator rather than a chain of many operators.
647///
648/// # Examples
649///
650/// ```
651/// use differential_dataflow::input::Input;
652///
653/// ::timely::example(|scope| {
654///
655///     let data = scope.new_collection_from(1 .. 10).1;
656///
657///     let odds = data.filter(|x| x % 2 == 1);
658///     let evens = data.filter(|x| x % 2 == 0);
659///
660///     differential_dataflow::collection::concatenate(scope, vec![odds, evens])
661///         .assert_eq(&data);
662/// });
663/// ```
664pub fn concatenate<G, D, R, C, I>(scope: &mut G, iterator: I) -> Collection<G, D, R, C>
665where
666    G: Scope,
667    D: Data,
668    R: Semigroup+'static,
669    C: Container + Clone + 'static,
670    I: IntoIterator<Item=Collection<G, D, R, C>>,
671{
672    scope
673        .concatenate(iterator.into_iter().map(|x| x.inner))
674        .as_collection()
675}