Skip to content

Instantly share code, notes, and snippets.

@Anamorphosee
Created January 27, 2023 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anamorphosee/017b2475f8b3e797a5897077da7e8143 to your computer and use it in GitHub Desktop.
Save Anamorphosee/017b2475f8b3e797a5897077da7e8143 to your computer and use it in GitHub Desktop.
loom sequence
@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())
}
}
@Anamorphosee
Copy link
Author

Run with --enable-preview --add-exports java.base/jdk.internal.vm=ALL-UNNAMED JVM arguments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment