# Streaming Generators?

**URL:** <https://internals.rust-lang.org/t/streaming-generators/5850>\
**Category:** language design\
**Created:** [September 1, 2017, 7:37pm UTC](https://internals.rust-lang.org/t/streaming-generators/5850 "2017-09-01T19:37:53Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mbrubeck/32/174_2.png) [@mbrubeck](https://internals.rust-lang.org/u/mbrubeck)\
**Post date:** [September 1, 2017, 7:37pm UTC](https://internals.rust-lang.org/t/streaming-generators/5850/1 "2017-09-01T19:37:54Z")

</div>

### Background: Streaming Iterators

Rust’s `Iterator` trait has a well-known restriction: `Iterator::next` only borrows the iterator temporarily, rather than for the life of the `Item` it yields. This makes methods like `collect` possible (because you can call `next` again while previously-yielded items are still alive), but on the other hand it’s not possible for an iterator to yield references to values that it owns, or to require that previous-yielded values are gone before a new value is yielded.

This means that certain types of iteration (called “streaming iterators” in Gankro’s [OMG ITERATORS](http://cglab.ca/~abeinges/talks/iter/) talk and elsewhere) can’t use the `Iterator` trait, and must use alternate traits like [StreamingIterator](https://docs.rs/streaming-iterator/0.1.2/streaming_iterator/). Streaming iterator traits are difficult to express generically without language extensions such as [associated type constructors](http://smallcultfollowing.com/babysteps/blog/2016/11/02/associated-type-constructors-part-1-basic-concepts-and-introduction/) (ATC).

### Streaming Generators

The new [Generator trait](https://internals.rust-lang.org/t/help-test-async-await-generators-coroutines/5835/22) suffers from the same limitation, for the same reasons: `Generator::resume` cannot borrow the generator for the lifetime of the yielded value. With the ATC syntax proposed by [RFC 1598](https://github.com/rust-lang/rfcs/pull/1598), we could instead write a generator trait that allows arbitrary “streaming” generators:

```rust
pub trait Generator {
    type Yield<'item>;
    type Return<'item>;
    fn resume<'item>(&'item mut self) -> GeneratorState<Self::Yield<'item>, Self::Return<'item>>;
}

```

The compiler would need the ability to infer appropriate lifetimes for the associated types of generator literals. (This is a problem that doesn’t apply to streaming iterators, since we don’t have iterator literals.)

Allowing streaming generators would complicate generic code that only works with non-streaming generators, for example `collect`-like functions that repeatedly call a generator while keeping previously-yielded values alive. Such functions would need a bound to express that the `Yield` and/or `Return` type is _not_ limited to the `'item` lifetime. On IRC, @withoutboats gave a possible solution using implication bounds (which are not part of the language today, but are possible in [Chalk](https://github.com/nikomatsakis/chalk/)).

### Motivating Examples

These are examples of code that someone might want to write, but can’t with the current experimental generator features.

Example 1 ([playground](https://play.rust-lang.org/?gist=7a3e233988d771788ab67ae1d53ee14b&version=nightly)): A generator that returns references to data that it owns, to avoid allocating new resources for each yielded item:

```rust
    let lines = || {
        let mut f = BufReader::new(File::open("data.txt")?);
        let mut s = String::new();
        loop {
            s.clear();
            match f.read_line(&mut s) {
                Err(e) => return Err(e),
                Ok(0) => return Ok(()),
                Ok(_) => yield &s[..],
            }
        }
    };

```

Example 2 ([playground](https://play.rust-lang.org/?gist=412012b81b902b09638554a7d9a1fe62&version=nightly)): A generator that yields mutable references to the same data more than once, with a user that keeps only one yielded item alive at a time:

```rust
    struct Player;
    
    impl Player {
        fn take_turn(&mut self) {}
    }

    let mut player1 = Player;
    let mut player2 = Player;
    
    let mut turns = || {
        loop {
            yield &mut player1;
            yield &mut player2;
        }
    };
    
    while let Yielded(player) = turns.resume() {
        player.take_turn();
    }

```

I think these examples show that if streaming generators were available, they could also address many of the use cases for streaming iterators.

### Borrow Checking

Currently, the body of a generator cannot contain any borrows that persist across a `yield`, because these may be invalidated if the generator is moved while suspended. (This affects “Example 1” above.) However, if `resume` borrows the generator for the lifetime of the yielded item, then the generator is guaranteed not to move for at least that lifetime. Therefore, I think, this restriction could be relaxed as long as any borrows that exist at a yield point have lifetimes no longer than the yielded type.

I think [non-lexical lifetimes](https://github.com/rust-lang/rfcs/pull/2094) might also be important for allowing code like the examples above, but I haven’t dug into this further.

### Questions

1. Are streaming generators both feasible and worth supporting?
2. If so, should there be a single `Generator` trait that supports both streaming and non-streaming generators, or two separate traits?
3. If the current non-streaming `Generator` trait were stabilized as-is, would it cause any problems for adding streaming generator support later?

---

<div class="post-metadata">

**Author:** ![vadimcn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/vadimcn/32/2789_2.png) [@vadimcn](https://internals.rust-lang.org/u/vadimcn)\
**Post date:** [September 1, 2017, 8:23pm UTC](https://internals.rust-lang.org/t/streaming-generators/5850/2 "2017-09-01T20:23:02Z")

</div>

> [@mbrubeck](#):
>
> However, if resume borrows the generator for the lifetime of the yielded item, then the generator is guaranteed not to move for at least that lifetime. Therefore, I think, this restriction could be relaxed as long as any borrows that exist at a yield point have lifetimes no longer than the yielded type.

Would that work? If I drop the reference I got from resume(), the generator becomes "unborrowed", so I'd be free to move it, wouldn't I?

---

<div class="post-metadata">

**Author:** ![ExpHP](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/exphp/32/6208_2.png) [@ExpHP](https://internals.rust-lang.org/u/ExpHP)\
**Post date:** [September 2, 2017, 8:39pm UTC](https://internals.rust-lang.org/t/streaming-generators/5850/3 "2017-09-02T20:39:01Z")

</div>

On a related note, I just happened to accidentally visit the issues page, where I noticed this:

> <https://github.com/rust-lang/rust/issues/44265>
>
> This is a tracking issue for generic associated types (rust-lang/rfcs#1598)
> TODO:
> Implement (mentoring instructions here)
> Document
> Stabilize
> Blocking bugs
> #62521
> #30472
> #67509
> #67510
> ...

I think we need some sort of town crier to sound a big, blaring blow horn whenever an RFC gets accepted.

---

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mbrubeck/32/174_2.png) [@mbrubeck](https://internals.rust-lang.org/u/mbrubeck)\
**Post date:** [March 25, 2019, 8:28am UTC](https://internals.rust-lang.org/t/streaming-generators/5850/4 "2019-03-25T08:28:57Z")

</div>

Closed on March 25, 2019, 8:28am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
