1 /* 2 * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.serialization.protobuf 6 7 import kotlinx.serialization.* 8 import kotlin.test.* 9 10 class ScatteredArraysTest { 11 @Serializable 12 data class ListData(val data: List<String>, val separator: String) 13 14 @Serializable 15 data class ByteData(val data: ByteArray, val separator: String) { equalsnull16 override fun equals(other: Any?): Boolean { 17 if (this === other) return true 18 if (other !is ByteData) return false 19 20 if (!data.contentEquals(other.data)) return false 21 if (separator != other.separator) return false 22 23 return true 24 } 25 hashCodenull26 override fun hashCode(): Int { 27 var result = data.contentHashCode() 28 result = 31 * result + separator.hashCode() 29 return result 30 } 31 } 32 prepareListTestDatanull33 private fun prepareListTestData(): String { 34 // Concatenate two serialized representations 35 // Resulting bytes would be [1, 2, foo, 3, bar] 36 // Protobuf per spec must read it as ListData([1,2,3], bar) 37 val d1 = ListData(listOf("1", "2"), "foo") 38 val d2 = ListData(listOf("3"), "bar") 39 return ProtoBuf.encodeToHexString(ListData.serializer(), d1) + 40 ProtoBuf.encodeToHexString(ListData.serializer(), d2) 41 } 42 prepareByteTestDatanull43 private fun prepareByteTestData(): String { 44 // Concatenate two serialized representations 45 // Resulting bytes would be [1, 2, foo, 3, bar] 46 // Protobuf per spec must read it as ByteData([1,2,3], bar) 47 val d1 = ByteData(byteArrayOf(1, 2), "foo") 48 val d2 = ByteData(byteArrayOf(3), "bar") 49 return ProtoBuf.encodeToHexString(ByteData.serializer(), d1) + 50 ProtoBuf.encodeToHexString(ByteData.serializer(), d2) 51 } 52 doTestnull53 private fun <T> doTest(serializer: KSerializer<T>, testData: String, goldenValue: T) { 54 val parsed = ProtoBuf.decodeFromHexString(serializer, testData) 55 assertEquals(goldenValue, parsed) 56 } 57 58 @Test testListDatanull59 fun testListData() = 60 doTest(ListData.serializer(), prepareListTestData(), ListData(listOf("1", "2", "3"), "bar")) 61 62 @Test 63 fun testByteData() = 64 doTest(ByteData.serializer(), prepareByteTestData(), ByteData(byteArrayOf(1, 2, 3), "bar")) 65 } 66