Skip to content

Commit

Permalink
Fix PotionEffectType serializer too
Browse files Browse the repository at this point in the history
  • Loading branch information
0ffz committed Jan 18, 2024
1 parent 6961fe3 commit 8d6132a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,24 @@ package com.mineinabyss.idofront.serialization

import com.mineinabyss.idofront.util.toMCKey
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import org.bukkit.Registry
import org.bukkit.potion.PotionEffectType

@JvmInline
@Serializable
@SerialName("PotionEffectType")
private value class PotionEffectTypeSurrogate(val type: String) {

init {
require(type.isNotBlank() && Registry.POTION_EFFECT_TYPE.get(type.toMCKey()) != null) { "PotionEffectType must be valid" }
}
}

object PotionEffectTypeSerializer : KSerializer<PotionEffectType> {
override val descriptor: SerialDescriptor = PotionEffectTypeSurrogate.serializer().descriptor
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("PotionEffectType", PrimitiveKind.STRING)

override fun serialize(encoder: Encoder, value: PotionEffectType) {
val surrogate = PotionEffectTypeSurrogate(value.key.asString())
encoder.encodeSerializableValue(PotionEffectTypeSurrogate.serializer(), surrogate)
encoder.encodeString(value.key.asString())
}

override fun deserialize(decoder: Decoder): PotionEffectType {
val surrogate = decoder.decodeSerializableValue(PotionEffectTypeSurrogate.serializer())
return Registry.POTION_EFFECT_TYPE.get(surrogate.type.toMCKey())!!
val name = decoder.decodeString()
val type = name.toMCKey()
return Registry.POTION_EFFECT_TYPE.get(type) ?: throw IllegalArgumentException("Invalid potion type: $name")
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.mineinabyss.idofront.serialization

import com.mineinabyss.idofront.util.toMCKey
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
Expand All @@ -19,7 +20,7 @@ object PotionTypeSerializer : KSerializer<PotionType> {

override fun deserialize(decoder: Decoder): PotionType {
val name = decoder.decodeString()
val type = NamespacedKey.fromString(name) ?: throw IllegalArgumentException("Invalid potion type: $name")
val type = name.toMCKey()
return Registry.POTION.get(type) ?: throw IllegalArgumentException("Invalid potion type: $name")
}
}

0 comments on commit 8d6132a

Please sign in to comment.