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

commonMain.cache.DataCacheView.kt Maven / Gradle / Ivy

There is a newer version: 0.15.0
Show newest version
package dev.kord.core.cache

import dev.kord.cache.api.DataCache
import dev.kord.cache.api.DataEntryCache
import dev.kord.cache.api.Query
import dev.kord.cache.api.QueryBuilder
import dev.kord.cache.api.data.DataDescription
import kotlin.reflect.KProperty1
import kotlin.reflect.KType

public class ViewKeys(private val keySet: MutableSet = mutableSetOf()) {
    public val keys: Set = keySet

    public fun add(key: Any) {
        keySet.add(key)
    }
}

/**
 * A [DataCacheView] that limits removal of cached instances to those inserted in this cache,
 * and not the underlying [cache].
 */
public class DataCacheView(private val cache: DataCache) : DataCache by cache {
    private val keys = ViewKeys()
    private val descriptions = mutableMapOf>()

    @Suppress("UNCHECKED_CAST")
    private fun  getDescription(type: KType) = descriptions[type]!! as DataDescription

    override suspend fun register(description: DataDescription) {
        descriptions[description.type] = description
    }

    override suspend fun register(vararg descriptions: DataDescription) {
        descriptions.forEach { register(it) }
    }

    override suspend fun register(descriptions: Iterable>) {
        descriptions.forEach { register(it) }
    }

    override fun  getEntry(type: KType): DataEntryCache? {
        return cache.getEntry(type)?.let { DataEntryCacheView(it, getDescription(type), keys) }
    }

    override fun toString(): String {
        return "DataCacheView(cache=$cache)"
    }

}

private class DataEntryCacheView(
    private val entryCache: DataEntryCache,
    private val description: DataDescription,
    private val viewKeys: ViewKeys
) : DataEntryCache by entryCache {

    override suspend fun put(item: T) {
        entryCache.put(item)
        viewKeys.add(description.indexField.property.get(item))
    }

    override fun query(): QueryBuilder {
        return QueryBuilderView(entryCache.query(), description.indexField.property, viewKeys.keys)
    }

}

private class QueryBuilderView(
    private val builder: QueryBuilder,
    private val property: KProperty1,
    private val keys: Set
) : QueryBuilder by builder {
    override fun build(): Query = QueryView(builder, property, keys)
}

private class QueryView(
    private val builder: QueryBuilder,
    private val property: KProperty1,
    private val keys: Set
) : Query by builder.build() {
    override suspend fun remove() = builder.apply { property `in` keys }.build().remove()
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy