Created
January 27, 2023 13:43
-
-
Save Anamorphosee/017b2475f8b3e797a5897077da7e8143 to your computer and use it in GitHub Desktop.
loom sequence
This file contains hidden or 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
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") | |
import jdk.internal.vm.Continuation | |
import jdk.internal.vm.ContinuationScope | |
internal class Wrapper<T>(val value: T) | |
class SequenceScope<T>( | |
private val seq: Sequence<T> | |
) { | |
fun emit(value: T) { | |
seq.buffer = Wrapper(value) | |
Continuation.yield(seq.continuationScope) | |
} | |
} | |
class Sequence<T>(private val generator: SequenceScope<T>.() -> Unit) { | |
internal val continuationScope = ContinuationScope("loom action") | |
private var finished = false | |
private val continuation = Continuation(continuationScope) { | |
scope.generator() | |
finished = true | |
} | |
private val scope = SequenceScope(this) | |
internal var buffer: Wrapper<T>? = null | |
fun hasNext(): Boolean { | |
if (buffer != null) { | |
return true | |
} | |
if (finished) { | |
return false | |
} | |
generateNext() | |
return buffer != null | |
} | |
fun next(): T { | |
if (!hasNext()) { | |
throw NoSuchElementException() | |
} | |
val next = buffer!!.value | |
buffer = null | |
return next | |
} | |
private fun generateNext() { | |
continuation.run() | |
} | |
} | |
fun main() { | |
val fib = Sequence { | |
var prev = 0L | |
var curr = 1L | |
while (true) { | |
emit(curr) | |
val tmp = curr | |
curr += prev | |
prev = tmp | |
} | |
} | |
for (i in 0..10) { | |
println(fib.next()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run with
--enable-preview --add-exports java.base/jdk.internal.vm=ALL-UNNAMED
JVM arguments