All Downloads are FREE. Search and download functionalities are using the official Maven repository.

main.wisp.resources.MemoryResourceLoaderBackend.kt Maven / Gradle / Ivy

There is a newer version: 2024.11.18.181619-bc85d02
Show newest version
package wisp.resources

import okio.Buffer
import okio.BufferedSource
import okio.ByteString
import java.util.*

/**
 * Read-write resources stored only in memory. Most useful for testing. It is possible to have
 * multiple instances of this backend.
 *
 * This uses the scheme `memory:`.
 */
class MemoryResourceLoaderBackend : ResourceLoader.Backend() {
    private val resources = TreeMap()
    private var resourceChangedListeners = mutableMapOf Unit>()

    override fun open(path: String): BufferedSource? {
        val resource = resources[path] ?: return null
        return Buffer().write(resource)
    }

    override fun put(path: String, data: ByteString) {
        resources[path] = data
        resourceChanged(SCHEME, path)
    }

    override fun exists(path: String) = resources[path] != null

    override fun all(): Set = resources.keys

    override fun watch(path: String, resourceChangedListener: (address: String) -> Unit) {
        resourceChangedListeners[path] = resourceChangedListener
    }

    override fun unwatch(path: String) {
        resourceChangedListeners.remove(path)
    }

    fun resourceChanged(scheme: String, path: String) {
        val resourceChangedListener = resourceChangedListeners[path]
        if (resourceChangedListener != null) {
            resourceChangedListener(scheme + path)
        }
    }

    companion object {
        const val SCHEME = "memory:"
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy