Class Subspace :: sus :: iter :: Generator

template <class T>
class Generator final
{ ... };

A generator type that is a sus::iter::Iterator over type T.

To implement a generator iterator, write a function that returns sus::iter::Generator<T> and call it. The function can co_yield values of type T, and each one will be returned from the resulting Iterator in the same order.

Example

auto generate_fibonacci = []() -> Generator<i32> {
  co_yield 0;
  i32 n1 = 0, n2 = 1;
  while (true) {
    i32 next = n1 + n2;
    n1 = n2;
    n2 = next;
    co_yield n1;
  }
};

// Directly using the generator iterator, in a for loop.
sus::Vec<i32> v;
for (i32 i : generate_fibonacci().take(7u)) {
  v.push(i);
}
sus_check(v == sus::Vec<i32>(0, 1, 1, 2, 3, 5, 8));

// Using `from_generator`, with collect.
sus::Vec<i32> v2 = generate_fibonacci().take(7u).collect_vec();
sus_check(v2 == sus::Vec<i32>(0, 1, 1, 2, 3, 5, 8));

Static Methods

sus::mem::Move trait.

Methods

auto begin() & -> auto

Adaptor method for using Generator in ranged for loops.

This replaces the implementation in IteratorBase with something more efficient, as the yielded T from the generator must be held in the promise, and this avoids moving it and holding it in the type returned by begin() as well.

auto next() -> Option<T>

sus::iter::Iterator trait.

auto size_hint() const -> SizeHint

sus::iter::Iterator trait.

Operators

auto operator=(Generator<Item>&& o) -> Generator<Item>&

sus::mem::Move trait.