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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
use {
    receipt,
    Async,
    Pair,
    Future,
    Complete,
    Cancel,
    Receipt,
    AsyncResult,
    AsyncError
};
use super::core::{self, Core};
use std::fmt;

/*
 *
 * ===== Stream =====
 *
 */

#[must_use = "streams are lazy and do nothing unless consumed"]
pub struct Stream<T: Send + 'static, E: Send + 'static> {
    core: Option<Core<Head<T, E>, E>>,
}

/// Convenience type alias for the realized head of a stream
pub type Head<T, E> = Option<(T, Stream<T, E>)>;

// Shorthand for the core type for Streams
pub type StreamCore<T, E> = Core<Head<T, E>, E>;

impl<T: Send + 'static, E: Send + 'static> Stream<T, E> {

    /// Creates a new `Stream`, returning it with the associated `Sender`.
    pub fn pair() -> (Sender<T, E>, Stream<T, E>) {
        let core = Core::new();
        let stream = Stream { core: Some(core.clone()) };

        (Sender { core: Some(core) }, stream)
    }

    /// Returns a Stream that will immediately succeed with the supplied value.
    ///
    /// ```
    /// use eventual::*;
    ///
    /// let stream = Stream::<i32, &'static str>::empty();
    /// assert!(stream.iter().next().is_none());
    /// ```
    pub fn empty() -> Stream<T, E> {
        Stream { core: Some(Core::with_value(Ok(None))) }
    }

    /// Asyncronously collects the items from the `Stream`, returning them sorted by order of
    /// arrival.
    pub fn collect(self) -> Future<Vec<T>, E> {
        let buffer = Vec::new();
        self.reduce(buffer, |mut vec, item| { vec.push(item); return vec })
    }

    /// Synchronously iterate over the `Stream`
    pub fn iter(mut self) -> StreamIter<T, E> {
        StreamIter { core: Some(core::take(&mut self.core)) }
    }

    /*
     *
     * ===== Computation Builders =====
     *
     */

    /// Sequentially yields each value to the supplied function. Returns a
    /// future representing the completion of the final yield.
    pub fn each<F: FnMut(T) + Send + 'static>(self, f: F) -> Future<(), E> {
        let (complete, ret) = Future::pair();

        complete.receive(move |res| {
            if let Ok(complete) = res {
                self.do_each(f, complete);
            }
        });

        ret
    }

    // Perform the iteration
    fn do_each<F: FnMut(T) + Send + 'static>(self, mut f: F, complete: Complete<(), E>) {
        self.receive(move |head| {
            match head {
                Ok(Some((v, rest))) => {
                    f(v);
                    rest.do_each(f, complete);
                }
                Ok(None) => {
                    complete.complete(());
                }
                Err(AsyncError::Failed(e)) => {
                    complete.fail(e);
                }
                _ => {}
            }
        });
    }

    /// Returns a new stream containing the values of the original stream that
    /// match the given predicate.
    pub fn filter<F: FnMut(&T) -> bool + Send + 'static>(self, f: F) -> Stream<T, E> {
        let (sender, stream) = Stream::pair();
        self.do_filter(f, sender);
        stream
    }

    fn do_filter<F, A>(self, mut f: F, sender: A)
            where F: FnMut(&T) -> bool + Send + 'static,
                  A: Async<Value=Sender<T, E>> {

        // Wait for the consumer to express interest
        sender.receive(move |res| {
            if let Ok(sender) = res {
                self.receive(move |head| {
                    match head {
                        Ok(Some((v, rest))) => {
                            if f(&v) {
                                rest.do_filter(f, sender.send(v));
                            } else {
                                rest.do_filter(f, sender);
                            }
                        }
                        Ok(None) => {}
                        Err(AsyncError::Failed(e)) => sender.fail(e),
                        Err(AsyncError::Aborted) => sender.abort(),
                    }
                });
            }
        });
    }

    /// Returns a new stream representing the application of the specified
    /// function to each value of the original stream.
    pub fn map<F: FnMut(T) -> U + Send + 'static, U: Send + 'static>(self, mut f: F) -> Stream<U, E> {
        self.map_async(move |val| Ok(f(val)))
    }

    /// Returns a new stream representing the application of the specified
    /// function to each value of the original stream. Each iteration waits for
    /// the async result of the mapping to realize before continuing on to the
    /// next value.
    pub fn map_async<F, U>(self, action: F) -> Stream<U::Value, E>
            where F: FnMut(T) -> U + Send + 'static,
                  U: Async<Error=E> {

        let (sender, ret) = Stream::pair();

        sender.receive(move |res| {
            if let Ok(sender) = res {
                self.do_map(sender, action);
            }
        });

        ret
    }

    fn do_map<F, U>(self, sender: Sender<U::Value, E>, mut f: F)
            where F: FnMut(T) -> U + Send + 'static,
                  U: Async<Error=E> {

        self.receive(move |head| {
            match head {
                Ok(Some((v, rest))) => {
                    f(v).receive(move |res| {
                        match res {
                            Ok(val) => {
                                sender.send(val).receive(move |res| {
                                    if let Ok(sender) = res {
                                        rest.do_map(sender, f);
                                    }
                                });
                            }
                            Err(AsyncError::Failed(e)) => sender.fail(e),
                            Err(AsyncError::Aborted) => sender.abort(),
                        }
                    });
                }
                Ok(None) => {}
                Err(AsyncError::Failed(e)) => sender.fail(e),
                Err(AsyncError::Aborted) => sender.abort(),
            }
        });
    }

    /// Returns a new stream with an identical sequence of values as the
    /// original. If the original stream errors, apply the given function on
    /// the error and use the result as the error of the new stream.
    pub fn map_err<F, U>(self, f: F) -> Stream<T, U>
            where F: FnOnce(E) -> U + Send + 'static,
                  U: Send + 'static {
        let (sender, stream) = Stream::pair();

        sender.receive(move |res| {
            if let Ok(sender) = res {
                self.do_map_err(sender, f);
            }
        });

        stream
    }

    fn do_map_err<F, U>(self, sender: Sender<T, U>, f: F)
            where F: FnOnce(E) -> U + Send + 'static,
                  U: Send + 'static {
        self.receive(move |res| {
            match res {
                Ok(Some((val, rest))) => {
                    sender.send(val).receive(move |res| {
                        if let Ok(sender) = res {
                            rest.do_map_err(sender, f);
                        }
                    });
                }
                Ok(None) => {}
                Err(AsyncError::Failed(e)) => sender.fail(f(e)),
                Err(AsyncError::Aborted) => sender.abort(),
            }
        });
    }

    pub fn process<F, U>(self, in_flight: usize, f: F) -> Stream<U::Value, E>
            where F: FnMut(T) -> U + Send + 'static,
                  U: Async<Error=E> {
        use process::process;
        process(self, in_flight, f)
    }

    /// Aggregate all the values of the stream by applying the given function
    /// to each value and the result of the previous application. The first
    /// iteration is seeded with the given initial value.
    ///
    /// Returns a future that will be completed with the result of the final
    /// iteration.
    pub fn reduce<F: Fn(U, T) -> U + Send + 'static, U: Send + 'static>(self, init: U, f: F) -> Future<U, E> {
        self.reduce_async(init, move |curr, val| Ok(f(curr, val)))
    }

    /// Aggregate all the values of the stream by applying the given function
    /// to each value and the realized result of the previous application. The
    /// first iteration is seeded with the given initial value.
    ///
    /// Returns a future that will be completed with the result of the final
    /// iteration.
    pub fn reduce_async<F, U, X>(self, init: X, action: F) -> Future<X, E>
            // TODO: Remove X generic, blocked on rust-lang/rust#23728
            where F: Fn(X, T) -> U + Send + 'static,
                  U: Async<Value=X, Error=E>,
                  X: Send + 'static {

        let (sender, ret) = Future::pair();

        sender.receive(move |res| {
            if let Ok(sender) = res {
                self.do_reduce(sender, init, action);
            }
        });

        ret
    }

    fn do_reduce<F, U>(self, complete: Complete<U::Value, E>, curr: U::Value, f: F)
            where F: Fn(U::Value, T) -> U + Send + 'static,
                  U: Async<Error=E> {

        self.receive(move |head| {
            match head {
                Ok(Some((v, rest))) => {
                    f(curr, v).receive(move |res| {
                        match res {
                            Ok(curr) => rest.do_reduce(complete, curr, f),
                            Err(AsyncError::Failed(e)) => complete.fail(e),
                            Err(AsyncError::Aborted) => drop(complete),
                        }
                    });
                }
                Ok(None) => complete.complete(curr),
                Err(AsyncError::Failed(e)) => complete.fail(e),
                Err(AsyncError::Aborted) => drop(complete),
            }
        });
    }

    /// Returns a stream representing the `n` first values of the original
    /// stream.
    pub fn take(self, n: u64) -> Stream<T, E> {
        let (sender, stream) = Stream::pair();

        self.do_take(n, sender);
        stream
    }

    fn do_take<A>(self, n: u64, sender: A) where A: Async<Value=Sender<T, E>> {
        if n == 0 {
            return;
        }

        sender.receive(move |res| {
            if let Ok(sender) = res {
                self.receive(move |res| {
                    match res {
                        Ok(Some((v, rest))) => {
                            rest.do_take(n - 1, sender.send(v));
                        }
                        Ok(None) => {}
                        Err(AsyncError::Failed(e)) => sender.fail(e),
                        Err(AsyncError::Aborted) => sender.abort(),
                    }
                });
            }
        });
    }

    pub fn take_while<F>(self, _f: F) -> Stream<T, E>
            where F: Fn(&T) -> bool + Send + 'static {
        unimplemented!();
    }

    pub fn take_until<A>(self, cond: A) -> Stream<T, E>
            where A: Async<Error=E> {

        super::select((cond, self))
            .and_then(move |(i, (cond, stream))| {
                if i == 0 {
                    Ok(None)
                } else {
                    match stream.expect() {
                        Ok(Some((v, rest))) => {
                            Ok(Some((v, rest.take_until(cond))))
                        }
                        _ => Ok(None),
                    }
                }
            }).to_stream()
    }

    pub fn to_future(mut self) -> Future<Head<T, E>, E> {
        use super::future;
        future::from_core(core::take(&mut self.core))
    }

    /*
     *
     * ===== Internal Helpers =====
     *
     */

    fn from_core(core: StreamCore<T, E>) -> Stream<T, E> {
        Stream { core: Some(core) }
    }
}

impl<T: Send + 'static, E: Send + 'static> Async for Stream<T, E> {
    type Value = Head<T, E>;
    type Error = E;
    type Cancel = Receipt<Stream<T, E>>;

    fn is_ready(&self) -> bool {
        core::get(&self.core).consumer_is_ready()
    }

    fn is_err(&self) -> bool {
        core::get(&self.core).consumer_is_err()
    }

    fn poll(mut self) -> Result<AsyncResult<Head<T, E>, E>, Stream<T, E>> {
        let mut core = core::take(&mut self.core);

        match core.consumer_poll() {
            Some(res) => Ok(res),
            None => Err(Stream { core: Some(core) })
        }
    }

    fn ready<F: FnOnce(Stream<T, E>) + Send + 'static>(mut self, f: F) -> Receipt<Stream<T, E>> {
        let core = core::take(&mut self.core);

        match core.consumer_ready(move |core| f(Stream::from_core(core))) {
            Some(count) => receipt::new(core, count),
            None => receipt::none(),
        }
    }

    fn await(mut self) -> AsyncResult<Head<T, E>, E> {
        core::take(&mut self.core).consumer_await()
    }
}

impl<T: Send + 'static, E: Send + 'static> Pair for Stream<T, E> {
    type Tx = Sender<T, E>;

    fn pair() -> (Sender<T, E>, Stream<T, E>) {
        Stream::pair()
    }
}

impl<T: Send + 'static, E: Send + 'static> fmt::Debug for Stream<T, E> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Stream<?>")
    }
}

impl<T: Send + 'static, E: Send + 'static> Drop for Stream<T, E> {
    fn drop(&mut self) {
        if self.core.is_some() {
            core::take(&mut self.core).cancel();
        }
    }
}

impl<T: Send + 'static, E: Send + 'static> Cancel<Stream<T, E>> for Receipt<Stream<T, E>> {
    fn cancel(self) -> Option<Stream<T, E>> {
        let (core, count) = receipt::parts(self);

        if !core.is_some() {
            return None;
        }

        if core::get(&core).consumer_ready_cancel(count) {
            return Some(Stream { core: core });
        }

        None
    }
}

/*
 *
 * ===== Sender =====
 *
 */

/// The sending half of `Stream::pair()`. Can only be owned by a single task at
/// a time.
pub struct Sender<T: Send + 'static, E: Send + 'static> {
    core: Option<StreamCore<T, E>>,
}

impl<T: Send + 'static, E: Send + 'static> Sender<T, E> {

    // TODO: This fn would be nice to have, but isn't possible with the current
    // implementation of `send()` which requires the value slot of `Stream` to
    // always be available.
    //
    // I initially thought that `try_send` would be possible to implement if
    // the consumer was currently waiting for a value, but this doesn't work in
    // sync mode since the value is temporarily stored in the stream's value
    // slot and there would be a potential race condition.
    //
    // pub fn try_send(&self, val: T) -> Result<(), T>;

    /// Attempts to send a value to its `Stream`. Consumes self and returns a
    /// future representing the operation completing successfully and interest
    /// in the next value being expressed.
    pub fn send(mut self, val: T) -> BusySender<T, E> {
        let mut core = core::take(&mut self.core);
        let val = Some((val, Stream { core: Some(core.clone()) }));

        // Complete the value
        core.complete(Ok(val), false);
        BusySender { core: Some(core) }
    }

    /// Terminated the stream with the given error.
    pub fn fail(mut self, err: E) {
        core::take(&mut self.core).complete(Err(AsyncError::failed(err)), true);
    }

    /// Fails the paired `Stream` with a cancellation error. This will
    /// eventually go away when carllerche/syncbox#10 lands. It is currently
    /// needed to keep the state correct (see async::sequence)
    pub fn abort(mut self) {
        core::take(&mut self.core).complete(Err(AsyncError::aborted()), true);
    }

    /// Send + 'static all the values in the given source
    pub fn send_all<S: Source<Value=T>>(self, src: S) -> Future<Self, (S::Error, Self)> {
        src.send_all(self)
    }

    /*
     *
     * ===== Internal Helpers =====
     *
     */

    fn from_core(core: StreamCore<T, E>) -> Sender<T, E> {
        Sender { core: Some(core) }
    }
}

impl<T: Send + 'static, E: Send + 'static> Async for Sender<T, E> {
    type Value = Sender<T, E>;
    type Error = ();
    type Cancel = Receipt<Sender<T, E>>;

    fn is_ready(&self) -> bool {
        core::get(&self.core).producer_is_ready()
    }

    fn is_err(&self) -> bool {
        core::get(&self.core).producer_is_err()
    }

    fn poll(mut self) -> Result<AsyncResult<Sender<T, E>, ()>, Sender<T, E>> {
        debug!("Sender::poll; is_ready={}", self.is_ready());

        let core = core::take(&mut self.core);

        match core.producer_poll() {
            Some(res) => Ok(res.map(Sender::from_core)),
            None => Err(Sender { core: Some(core) })
        }
    }

    fn ready<F: FnOnce(Sender<T, E>) + Send + 'static>(mut self, f: F) -> Receipt<Sender<T, E>> {
        core::take(&mut self.core).producer_ready(move |core| {
            f(Sender::from_core(core))
        });

        receipt::none()
    }
}

impl<T: Send + 'static, E: Send + 'static> Drop for Sender<T, E> {
    fn drop(&mut self) {
        if self.core.is_some() {
            debug!("Sender::drop(); cancelling future");
            // Get the core
            let mut core = core::take(&mut self.core);
            core.complete(Ok(None), true);
        }
    }
}

/*
 *
 * ===== BusySender =====
 *
 */

pub struct BusySender<T: Send + 'static, E: Send + 'static> {
    core: Option<StreamCore<T, E>>,
}

impl<T: Send + 'static, E: Send + 'static> BusySender<T, E> {
    /*
     *
     * ===== Internal Helpers =====
     *
     */

    fn from_core(core: StreamCore<T, E>) -> BusySender<T, E> {
        BusySender { core: Some(core) }
    }
}

impl<T: Send + 'static, E: Send + 'static> Async for BusySender<T, E> {
    type Value = Sender<T, E>;
    type Error = ();
    type Cancel = Receipt<BusySender<T, E>>;

    fn is_ready(&self) -> bool {
        core::get(&self.core).consumer_is_ready()
    }

    fn is_err(&self) -> bool {
        core::get(&self.core).consumer_is_err()
    }

    fn poll(mut self) -> Result<AsyncResult<Sender<T, E>, ()>, BusySender<T, E>> {
        debug!("Sender::poll; is_ready={}", self.is_ready());

        let core = core::take(&mut self.core);

        match core.producer_poll() {
            Some(res) => Ok(res.map(Sender::from_core)),
            None => Err(BusySender { core: Some(core) })
        }
    }

    fn ready<F: FnOnce(BusySender<T, E>) + Send + 'static>(mut self, f: F) -> Receipt<BusySender<T, E>> {
        core::take(&mut self.core).producer_ready(move |core| {
            f(BusySender::from_core(core))
        });

        receipt::none()
    }
}

impl<T: Send + 'static, E: Send + 'static> Drop for BusySender<T, E> {
    fn drop(&mut self) {
        if self.core.is_some() {
            let core = core::take(&mut self.core);

            core.producer_ready(|mut core| {
                if core.producer_is_ready() {
                    core.complete(Ok(None), true);
                }
            });
        }
    }
}

impl<T: Send + 'static, E: Send + 'static> fmt::Debug for Sender<T, E> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Sender<?>")
    }
}

/*
 *
 * ===== Sink / Source =====
 *
 */

pub trait Source {
    type Value: Send + 'static;
    type Error: Send + 'static;

    fn send_all<E2: Send + 'static>(self, sender: Sender<Self::Value, E2>) ->
        Future<Sender<Self::Value, E2>, (Self::Error, Sender<Self::Value, E2>)>;
}

impl<T: Send + 'static, E: Send + 'static> Source for Future<T, E> {
    type Value = T;
    type Error = E;

    fn send_all<E2: Send + 'static>(self, sender: Sender<T, E2>) -> Future<Sender<T, E2>, (E, Sender<T, E2>)> {
        let (tx, rx) = Future::pair();

        self.receive(move |res| {
            match res {
                Ok(val) => {
                    sender.send(val).receive(move |res| {
                        if let Ok(sender) = res {
                            tx.complete(sender);
                        }
                    });
                }
                Err(AsyncError::Failed(e)) => tx.fail((e, sender)),
                Err(AsyncError::Aborted) => drop(tx),
            }
        });

        rx
    }
}

impl<T: Send + 'static, E: Send + 'static> Source for Stream<T, E> {
    type Value = T;
    type Error = E;

    fn send_all<E2: Send + 'static>(self, sender: Sender<T, E2>) -> Future<Sender<T, E2>, (E, Sender<T, E2>)> {
        let (tx, rx) = Future::pair();
        send_stream(self, sender, tx);
        rx
    }
}

// Perform the send
fn send_stream<T: Send + 'static, E: Send + 'static, E2: Send + 'static>(
    src: Stream<T, E>,
    dst: Sender<T, E2>,
    complete: Complete<Sender<T, E2>, (E, Sender<T, E2>)>) {

    src.receive(move |res| {
        match res {
            Ok(Some((val, rest))) => {
                dst.send(val).receive(move |res| {
                    if let Ok(dst) = res {
                        send_stream(rest, dst, complete);
                    }
                });
            }
            Ok(None) => complete.complete(dst),
            Err(AsyncError::Failed(e)) => complete.fail((e, dst)),
            Err(AsyncError::Aborted) => drop(complete),
        }
    })
}

/*
 *
 * ===== Receipt<Sender<T, E>> =====
 *
 */

impl<T: Send + 'static, E: Send + 'static> Cancel<Sender<T, E>> for Receipt<Sender<T, E>> {
    fn cancel(self) -> Option<Sender<T, E>> {
        None
    }
}

/*
 *
 * ===== Receipt<BusySender<T, E>> =====
 *
 */

impl<T: Send + 'static, E: Send + 'static> Cancel<BusySender<T, E>> for Receipt<BusySender<T, E>> {
    fn cancel(self) -> Option<BusySender<T, E>> {
        None
    }
}

/*
 *
 * ===== StreamIter =====
 *
 */

pub struct StreamIter<T: Send + 'static, E: Send + 'static> {
    core: Option<StreamCore<T, E>>,
}

impl<T: Send + 'static, E: Send + 'static> Iterator for StreamIter<T, E> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        use std::mem;

        match core::get_mut(&mut self.core).consumer_await() {
            Ok(Some((h, mut rest))) => {
                mem::replace(&mut self.core, Some(core::take(&mut rest.core)));
                Some(h)
            }
            Ok(None) => {
                let _ = core::take(&mut self.core);
                None
            }
            Err(_) => unimplemented!(),
        }
    }
}

impl<T: Send + 'static, E: Send + 'static> Drop for StreamIter<T, E> {
    fn drop(&mut self) {
        if self.core.is_some() {
            core::take(&mut self.core).cancel();
        }
    }
}

pub fn from_core<T: Send + 'static, E: Send + 'static>(core: StreamCore<T, E>) -> Stream<T, E> {
    Stream { core: Some(core) }
}