Yokan / rebuild
Course 1 8624561

ProfileRegistry.ios.kt

composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileRegistry.ios.kt

implementation44 lines
1@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class, kotlinx.cinterop.BetaInteropApi::class)23package eu.friedcutlet.yokan.app.profiles45import eu.friedcutlet.yokan.util.PlatformLock6import kotlinx.coroutines.Dispatchers7import kotlinx.coroutines.withContext8import platform.Foundation.NSDocumentDirectory9import platform.Foundation.NSFileManager10import platform.Foundation.NSNumber11import platform.Foundation.NSSearchPathForDirectoriesInDomains12import platform.Foundation.NSString13import platform.Foundation.NSUTF8StringEncoding14import platform.Foundation.NSUserDomainMask15import platform.Foundation.create16import platform.Foundation.stringWithContentsOfFile17import platform.Foundation.writeToFile1819actual fun createPlatformProfileRegistry(): ProfileRegistry {20    val documents = checkNotNull(NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true).firstOrNull() as? String)21    return ProfileRegistry(IosProfileRegistryPersistence("$documents/profiles/registry.json"))22}2324/** BGTasks and foreground scenes share this app process. Extensions must not mutate this registry. */25private class IosProfileRegistryPersistence(private val path: String) : ProfileRegistryPersistence {26    override suspend fun read(): String? = withContext(Dispatchers.Default) { lock.withLock { readLocked() } }27    override suspend fun compareAndSet(expected: String?, replacement: String): Boolean = withContext(Dispatchers.Default) {28        require(replacement.encodeToByteArray().size <= MaxProfileRegistryBytes)29        lock.withLock {30            if (readLocked() != expected) return@withLock false31            check(NSFileManager.defaultManager.createDirectoryAtPath(path.substringBeforeLast('/'), true, null, null))32            check(NSString.create(string = replacement).writeToFile(path, true, NSUTF8StringEncoding, null)) { "Profile registry write failed" }33            true34        }35    }36    private fun readLocked(): String? {37        val fm = NSFileManager.defaultManager38        if (!fm.fileExistsAtPath(path)) return null39        val size = fm.attributesOfItemAtPath(path, null)?.get(platform.Foundation.NSFileSize) as? NSNumber40        check(size != null && size.unsignedLongLongValue <= MaxProfileRegistryBytes.toULong()) { "Profile registry cannot be read safely" }41        return checkNotNull(NSString.stringWithContentsOfFile(path, NSUTF8StringEncoding, null)) { "Profile registry read failed" }42    }43    private companion object { val lock = PlatformLock() }44}45

Search chapters, reference and source filenames.