【Coroutines】Implement Python Generator by Kotlin Coroutines

Expected

a generator object that can generate sequence objects

and only generate object when consumer object request for it

kotlin 复制代码
fun main() {
    val generator = generator {
        yield(100)
        yield(200)
        yield(300)
    }
    while (generator.hasNext()) {
        val value = generator.await()
        println(value)
    }
}
Implementation
kotlin 复制代码
package com.code.kotlin

import kotlin.coroutines.*

@RestrictsSuspension
interface GeneratorScope<T> {

    suspend fun yield(value: T)
}

interface GeneratorIterator<T> : Iterator<T> {

    fun await(): T
}

internal interface Generator<T> : GeneratorScope<T>, GeneratorIterator<T>, Continuation<Any>

internal sealed class GeneratorState<T> {
    class WAITING<T>(val continuation: Continuation<Unit>) : GeneratorState<T>()
    class READY<T>(val continuation: Continuation<Unit>, val value: T) : GeneratorState<T>()
    class COMPLETED<T> : GeneratorState<T>()
}

internal class GeneratorImpl<T> : Generator<T> {

    override val context: CoroutineContext = EmptyCoroutineContext

    internal lateinit var state: GeneratorState<T>

    override suspend fun yield(value: T) {
        suspendCoroutine { continuation ->
            when (val _state = state) {
                is GeneratorState.WAITING -> {
                    state = GeneratorState.READY(continuation, value)
                }
                is GeneratorState.READY,
                is GeneratorState.COMPLETED -> throw IllegalStateException()
            }
        }
    }

    override fun resumeWith(result: Result<Any>) {
        state = GeneratorState.COMPLETED()
    }

    private fun resume() {
        when (val _state = state) {
            is GeneratorState.WAITING -> {
                _state.continuation.resume(Unit)
            }
            else -> {}
        }
    }

    override fun hasNext(): Boolean {
        resume()
        return state !is GeneratorState.COMPLETED
    }

    override fun next(): T {
        when (val _state = state) {
            is GeneratorState.READY -> {
                state = GeneratorState.WAITING(_state.continuation)
                return _state.value
            }
            is GeneratorState.WAITING,
            is GeneratorState.COMPLETED -> throw IllegalStateException()
        }
    }

    override fun await() = next()
}

fun <T> generator(
    block: suspend GeneratorScope<T>.() -> Unit
): GeneratorIterator<T> {
    val generator = GeneratorImpl<T>()
    val continuation = block.createCoroutine(generator, generator)
    generator.state = GeneratorState.WAITING(continuation)
    return generator
}
相关推荐
码界筑梦坊几秒前
130-基于Python的体育用品销售数据可视化分析系统
开发语言·python·信息可视化·flask·毕业设计
码界筑梦坊2 分钟前
131-基于Flask的美国新泽西州自动售货机销售数据可视化分析系统
开发语言·python·信息可视化·数据分析·flask·毕业设计
子榆.4 分钟前
CANN PyTorch适配器深度拆解:从.cuda()到.npu()到底发生了什么
人工智能·pytorch·python
chushiyunen5 分钟前
python使用笔记(linux环境)
linux·笔记·python
谢白羽7 分钟前
Voicebox 深度指南:开源本地 AI 语音工作室完整评测与上手教程
人工智能·python·开源·tts·voicebox
2401_8685347813 分钟前
论快速应用开发方法及应用
大数据·python
郝学胜-神的一滴15 分钟前
系统设计 012:从用户系统出发,吃透缓存、数据库与高并发设计
java·数据库·python·缓存·php·软件构建
人工智能导论实践课21 分钟前
奥比中光深度相机astra pro的初步ros包开发
人工智能·python
wj3055853789 小时前
课程 9:模型测试记录与 Prompt 策略
linux·人工智能·python·comfyui
星寂樱易李9 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python