Created
July 17, 2020 00:18
-
-
Save HaloFour/aaae9cd934ce09b2663299da76a7acc6 to your computer and use it in GitHub Desktop.
Generators in Loom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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