Skip to content

Instantly share code, notes, and snippets.

@HaloFour
Created July 17, 2020 00:18
Show Gist options
  • Save HaloFour/aaae9cd934ce09b2663299da76a7acc6 to your computer and use it in GitHub Desktop.
Save HaloFour/aaae9cd934ce09b2663299da76a7acc6 to your computer and use it in GitHub Desktop.
Generators in Loom
package sandbox;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
public class Generators {
private static final ContinuationScope continuationScope = new ContinuationScope("Generators");
public static <T> Iterable<T> createGenerator(Consumer<Consumer<T>> consumer) {
return () -> new Iterator<>() {
private boolean hasAdvanced;
private boolean hasNext;
private T next;
@Override
public boolean hasNext() {
return advance();
}
@Override
public T next() {
if (advance()) {
hasAdvanced = false;
return next;
} else {
throw new NoSuchElementException();
}
}
private final Continuation continuation = new Continuation(continuationScope, () -> {
resetState();
consumer.accept(this::onNext);
endOfIterator();
});
private void onNext(T value) {
hasAdvanced = hasNext = true;
next = value;
Continuation.yield(continuationScope);
resetState();
}
private void resetState() {
hasAdvanced = false;
hasNext = false;
next = null;
}
private void endOfIterator() {
hasAdvanced = true;
hasNext = false;
}
private boolean advance() {
if (hasAdvanced) {
return hasNext;
} else if (continuation.isDone()) {
return false;
} else {
continuation.run();
return hasNext;
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment