diff options
author | Linnea Gräf <nea@nea.moe> | 2025-01-29 00:26:56 +0100 |
---|---|---|
committer | Linnea Gräf <nea@nea.moe> | 2025-01-29 00:26:56 +0100 |
commit | 29857bff0875c43e055e89d34bc0d616d5d7dc4f (patch) | |
tree | 5875aed4144c0c1f004a86f6768eb5d6013d68f6 /src/main/kotlin/util | |
parent | ad03f074c603f38f9319411d785e598e8a92e42c (diff) | |
download | ultra-notifier-29857bff0875c43e055e89d34bc0d616d5d7dc4f.tar.gz ultra-notifier-29857bff0875c43e055e89d34bc0d616d5d7dc4f.tar.bz2 ultra-notifier-29857bff0875c43e055e89d34bc0d616d5d7dc4f.zip |
Diffstat (limited to 'src/main/kotlin/util')
-rw-r--r-- | src/main/kotlin/util/GsonUtil.kt | 55 | ||||
-rw-r--r-- | src/main/kotlin/util/KSerializable.kt | 112 | ||||
-rw-r--r-- | src/main/kotlin/util/iterutil.kt | 36 |
3 files changed, 203 insertions, 0 deletions
diff --git a/src/main/kotlin/util/GsonUtil.kt b/src/main/kotlin/util/GsonUtil.kt new file mode 100644 index 0000000..d689330 --- /dev/null +++ b/src/main/kotlin/util/GsonUtil.kt @@ -0,0 +1,55 @@ +package moe.nea.ultranotifier.util + +import com.google.gson.GsonBuilder +import com.google.gson.TypeAdapter +import com.google.gson.reflect.TypeToken +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import moe.nea.ultranotifier.datamodel.CategoryId +import moe.nea.ultranotifier.datamodel.ChatPattern +import moe.nea.ultranotifier.datamodel.ChatTypeId +import net.minecraft.util.Identifier +import util.KotlinTypeAdapterFactory +import java.io.File + +object GsonUtil { + val sharedGsonBuilder = GsonBuilder() + .registerTypeAdapterFactory(KotlinTypeAdapterFactory()) + .registerTypeHierarchyAdapter(Identifier::class.java, object : TypeAdapter<Identifier>() { + override fun write(out: JsonWriter, value: Identifier) { + out.value(value.namespace + ":" + value.path) + } + + override fun read(`in`: JsonReader): Identifier { + val identifierName = `in`.nextString() + val parts = identifierName.split(":") + require(parts.size != 2) { "$identifierName is not a valid identifier" } + return identifier(parts[0], parts[1]) + } + }.nullSafe()) + .registerTypeHierarchyAdapter(ChatPattern::class.java, stringWrapperAdapter(ChatPattern::text, ::ChatPattern)) + .registerTypeHierarchyAdapter(CategoryId::class.java, stringWrapperAdapter(CategoryId::id, ::CategoryId)) + .registerTypeHierarchyAdapter(ChatTypeId::class.java, stringWrapperAdapter(ChatTypeId::id, ::ChatTypeId)) + + private fun <T> stringWrapperAdapter(from: (T) -> String, to: (String) -> T): TypeAdapter<T> { + return object : TypeAdapter<T>() { + override fun write(out: JsonWriter, value: T) { + out.value(from(value)) + } + + override fun read(`in`: JsonReader): T { + return to(`in`.nextString()) + } + }.nullSafe() + } + + inline fun <reified T : Any> read(meta: File): T { + // TODO: add exception + meta.reader().use { reader -> + return gson.fromJson(reader, object : TypeToken<T>() {}.type) + } + } + + val gson = sharedGsonBuilder.create() + val prettyGson = sharedGsonBuilder.setPrettyPrinting().create() +} diff --git a/src/main/kotlin/util/KSerializable.kt b/src/main/kotlin/util/KSerializable.kt new file mode 100644 index 0000000..ef4c953 --- /dev/null +++ b/src/main/kotlin/util/KSerializable.kt @@ -0,0 +1,112 @@ +package util +import com.google.gson.* +import com.google.gson.annotations.SerializedName +import com.google.gson.reflect.TypeToken +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonToken +import com.google.gson.stream.JsonWriter +import kotlin.reflect.* +import kotlin.reflect.full.findAnnotation +import kotlin.reflect.full.isSubtypeOf +import kotlin.reflect.full.memberProperties +import kotlin.reflect.full.primaryConstructor +import kotlin.reflect.jvm.javaType +import com.google.gson.internal.`$Gson$Types` as InternalGsonTypes + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.CLASS) +annotation class KSerializable( +) + + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class ExtraData + + +class KotlinTypeAdapterFactory : TypeAdapterFactory { + + internal data class ParameterInfo( + val param: KParameter, + val adapter: TypeAdapter<Any?>, + val name: String, + val field: KProperty1<Any, Any?> + ) + + override fun <T : Any> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { + val kotlinClass = type.rawType.kotlin as KClass<T> + if (kotlinClass.findAnnotation<KSerializable>() == null) return null + if (!kotlinClass.isData) return null + val primaryConstructor = kotlinClass.primaryConstructor ?: return null + val params = primaryConstructor.parameters.filter { it.findAnnotation<ExtraData>() == null } + val extraDataParam = primaryConstructor.parameters + .find { it.findAnnotation<ExtraData>() != null } + ?.let { param -> + require(typeOf<MutableMap<String, JsonElement>>().isSubtypeOf(param.type)) + param to kotlinClass.memberProperties.find { it.name == param.name && it.returnType.isSubtypeOf(typeOf<Map<String, JsonElement>>()) } as KProperty1<Any, Map<String, JsonElement>> + } + val parameterInfos = params.map { param -> + ParameterInfo( + param, + gson.getAdapter( + TypeToken.get(InternalGsonTypes.resolve(type.type, type.rawType, param.type.javaType)) + ) as TypeAdapter<Any?>, + param.findAnnotation<SerializedName>()?.value ?: param.name!!, + kotlinClass.memberProperties.find { it.name == param.name }!! as KProperty1<Any, Any?> + ) + }.associateBy { it.name } + val jsonElementAdapter = gson.getAdapter(JsonElement::class.java) + + return object : TypeAdapter<T>() { + override fun write(out: JsonWriter, value: T?) { + if (value == null) { + out.nullValue() + return + } + out.beginObject() + parameterInfos.forEach { (name, paramInfo) -> + out.name(name) + paramInfo.adapter.write(out, paramInfo.field.get(value)) + } + if (extraDataParam != null) { + val extraData = extraDataParam.second.get(value) + extraData.forEach { (extraName, extraValue) -> + out.name(extraName) + jsonElementAdapter.write(out, extraValue) + } + } + out.endObject() + } + + override fun read(reader: JsonReader): T? { + if (reader.peek() == JsonToken.NULL) { + reader.nextNull() + return null + } + reader.beginObject() + val args = mutableMapOf<KParameter, Any?>() + val extraData = mutableMapOf<String, JsonElement>() + while (reader.peek() != JsonToken.END_OBJECT) { + val name = reader.nextName() + val paramData = parameterInfos[name] + if (paramData == null) { + extraData[name] = jsonElementAdapter.read(reader) + continue + } + val value = paramData.adapter.read(reader) + args[paramData.param] = value + } + reader.endObject() + if (extraDataParam == null) { + if (extraData.isNotEmpty()) { + throw JsonParseException("Encountered unknown keys ${extraData.keys} while parsing $type") + } + } else { + args[extraDataParam.first] = extraData + } + return primaryConstructor.callBy(args) + } + } + } +} + diff --git a/src/main/kotlin/util/iterutil.kt b/src/main/kotlin/util/iterutil.kt new file mode 100644 index 0000000..7845b05 --- /dev/null +++ b/src/main/kotlin/util/iterutil.kt @@ -0,0 +1,36 @@ +package moe.nea.ultranotifier.util + + +fun <T, K : Any> Sequence<T>.duplicatesBy(keyFunc: (T) -> K): Sequence<T> { + return object : Sequence<T> { + override fun iterator(): Iterator<T> { + val observed = HashSet<K>() + val oldIterator = this@duplicatesBy.iterator() + + return object : Iterator<T> { + var next: T? = null + var hasNext = false + override fun hasNext(): Boolean { + if (hasNext) return true + while (oldIterator.hasNext()) { + val elem = oldIterator.next() + val key = keyFunc(elem) + if (observed.add(key)) + continue + hasNext = true + next = elem + } + return hasNext + } + + override fun next(): T { + if (!hasNext()) throw NoSuchElementException() + hasNext = false + val elem = next as T + next = null + return elem + } + } + } + } +} |