-
Notifications
You must be signed in to change notification settings - Fork 618
/
GenericCustomSerializerTest.kt
79 lines (67 loc) · 2.86 KB
/
GenericCustomSerializerTest.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package kotlinx.serialization.features
import kotlinx.serialization.*
import kotlinx.serialization.internal.HexConverter
import kotlinx.serialization.json.JSON
import kotlin.test.Test
import kotlin.test.assertEquals
class CheckedData<T : Any>(val data: T, val checkSum: ByteArray) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as CheckedData<*>
if (data != other.data) return false
if (!checkSum.contentEquals(other.checkSum)) return false
return true
}
override fun hashCode(): Int {
var result = data.hashCode()
result = 31 * result + checkSum.contentHashCode()
return result
}
}
@Serializer(forClass = CheckedData::class)
class CheckedDataSerializer<T : Any>(val dataSerializer: KSerializer<T>) : KSerializer<CheckedData<T>> {
override fun serialize(output: Encoder, obj: CheckedData<T>) {
val out = output.beginStructure(descriptor)
out.encodeSerializableElement(descriptor, 0, dataSerializer, obj.data)
out.encodeStringElement(descriptor, 1, HexConverter.printHexBinary(obj.checkSum))
out.endStructure(descriptor)
}
override fun deserialize(input: Decoder): CheckedData<T> {
val inp = input.beginStructure(descriptor)
lateinit var data: T
lateinit var sum: ByteArray
loop@ while (true) {
when (val i = inp.decodeElementIndex(descriptor)) {
CompositeDecoder.READ_DONE -> break@loop
0 -> data = inp.decodeSerializableElement(descriptor, i, dataSerializer)
1 -> sum = HexConverter.parseHexBinary(inp.decodeStringElement(descriptor, i))
else -> throw SerializationException("Unknown index $i")
}
}
inp.endStructure(descriptor)
return CheckedData(data, sum)
}
}
@Serializable
data class StringData(@Serializable(with = CheckedDataSerializer::class) val data: CheckedData<String>)
@Serializable
data class IntData(@Serializable(with = CheckedDataSerializer::class) val data: CheckedData<Int>)
class GenericCustomSerializerTest {
@Test
fun testStringData() {
val original = StringData(CheckedData("my data", byteArrayOf(42, 32)))
val s = JSON.stringify(StringData.serializer(), original)
assertEquals("""{"data":{"data":"my data","checkSum":"2A20"}}""", s)
val restored = JSON.parse(StringData.serializer(), s)
assertEquals(original, restored)
}
@Test
fun testIntData() {
val original = IntData(CheckedData(42, byteArrayOf(42)))
val s = JSON.stringify(IntData.serializer(), original)
assertEquals("""{"data":{"data":42,"checkSum":"2A"}}""", s)
val restored = JSON.parse(IntData.serializer(), s)
assertEquals(original, restored)
}
}