summaryrefslogtreecommitdiff
path: root/formats/json/commonTest/src/kotlinx/serialization/features/inline/EncodeInlineElementTest.kt
blob: 037d7858b37334481beee5d5c947df8ce5893c26 (plain)
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
/*
 * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

@file:OptIn(ExperimentalUnsignedTypes::class)
/*
 * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.serialization.features.inline

import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.test.*
import kotlin.test.Test

@Serializable(WithUnsignedSerializer::class)
data class WithUnsigned(val u: UInt)

object WithUnsignedSerializer : KSerializer<WithUnsigned> {
    override fun serialize(encoder: Encoder, value: WithUnsigned) {
        val ce = encoder.beginStructure(descriptor)
        ce.encodeInlineElement(descriptor, 0).encodeInt(value.u.toInt())
        ce.endStructure(descriptor)
    }

    override fun deserialize(decoder: Decoder): WithUnsigned {
        val cd = decoder.beginStructure(descriptor)
        var u: UInt = 0.toUInt()
        loop@ while (true) {
            u = when (val i = cd.decodeElementIndex(descriptor)) {
                0 -> cd.decodeInlineElement(descriptor, i).decodeInt().toUInt()
                else -> break@loop
            }
        }
        cd.endStructure(descriptor)
        return WithUnsigned(u)
    }

    override val descriptor: SerialDescriptor = buildClassSerialDescriptor("WithUnsigned") {
        element("u", UInt.serializer().descriptor)
    }
}

class EncodeInlineElementTest {
    @Test
    fun wrapper() = noLegacyJs {
        val w = WithUnsigned(Int.MAX_VALUE.toUInt() + 1.toUInt())
        assertStringFormAndRestored("""{"u":2147483648}""", w, WithUnsignedSerializer, printResult = true)
    }
}