Yokan / rebuild
Course 1 8624561

QuickJsJavaScriptEngine.ios.kt

composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/QuickJsJavaScriptEngine.ios.kt

implementation67 lines
1@file:OptIn(ExperimentalCoroutinesApi::class, kotlinx.cinterop.BetaInteropApi::class)23package eu.friedcutlet.yokan.services.extensions.js45import kotlinx.cinterop.autoreleasepool6import kotlinx.coroutines.CloseableCoroutineDispatcher7import kotlinx.coroutines.Dispatchers8import kotlinx.coroutines.ExperimentalCoroutinesApi9import kotlinx.coroutines.Runnable10import platform.Foundation.NSCondition11import platform.Foundation.NSThread12import kotlin.coroutines.CoroutineContext1314// zipline builds QuickJS for Kotlin/Native without optimization, so one JS call costs ~22 KiB of15// native stack here versus ~1 KiB on the JVM; 128 MiB buys ~5,900 levels (8 MiB would be ~370).16// Stack pages are only committed as deep JS actually touches them.17internal actual const val QuickJsMaxStackSizeBytes: Long = 128L * 1024L * 1024L1819// Kotlin/Native workers (newSingleThreadContext) run on default 512 KiB pthread stacks, far below the20// QuickJS limit, so each engine gets an NSThread with an explicit stack size instead.21internal actual fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher = NSThreadDispatcher(stackBytes)2223private class NSThreadDispatcher(stackBytes: Long) : CloseableCoroutineDispatcher() {24    private val condition = NSCondition()25    private val tasks = ArrayDeque<Runnable>()26    private var closed = false2728    init {29        NSThread { runTasks() }.apply {30            name = "quickjs"31            stackSize = stackBytes.toULong()32            start()33        }34    }3536    override fun dispatch(context: CoroutineContext, block: Runnable) {37        condition.lock()38        val accepted = !closed39        if (accepted) {40            tasks.addLast(block)41            condition.signal()42        }43        condition.unlock()44        // Like a shut-down JVM executor: late continuations (cancelled zipline jobs) finish elsewhere.45        if (!accepted) Dispatchers.Default.dispatch(context, block)46    }4748    /** Lets the thread finish the queued tasks, then exit. */49    override fun close() {50        condition.lock()51        closed = true52        condition.signal()53        condition.unlock()54    }5556    private fun runTasks() {57        while (true) {58            condition.lock()59            while (tasks.isEmpty() && !closed) condition.wait()60            val task = tasks.removeFirstOrNull()61            condition.unlock()62            if (task == null) return63            // Host bridge calls create Objective-C objects; this thread has no run loop to drain them.64            autoreleasepool { task.run() }65        }66    }67}68

Search chapters, reference and source filenames.