Skip to content

Commit 3310495

Browse files
authored
Add stable hashCode()/equals() calculation to PrimitiveSerialDescriptor (#2136)
Fixes #2135
1 parent dc950f5 commit 3310495

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

core/commonMain/src/kotlinx/serialization/internal/Primitives.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ internal class PrimitiveSerialDescriptor(
5858
override fun getElementDescriptor(index: Int): SerialDescriptor = error()
5959
override fun getElementAnnotations(index: Int): List<Annotation> = error()
6060
override fun toString(): String = "PrimitiveDescriptor($serialName)"
61+
override fun equals(other: Any?): Boolean {
62+
if (this === other) return true
63+
if (other !is PrimitiveSerialDescriptor) return false
64+
if (serialName == other.serialName && kind == other.kind) return true
65+
return false
66+
}
67+
override fun hashCode() = serialName.hashCode() + 31 * kind.hashCode()
6168
private fun error(): Nothing = throw IllegalStateException("Primitive descriptor does not have elements")
6269
}
6370

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package kotlinx.serialization
2+
3+
import kotlinx.serialization.descriptors.PrimitiveKind
4+
import kotlinx.serialization.internal.PrimitiveSerialDescriptor
5+
import kotlin.test.Test
6+
import kotlin.test.assertEquals
7+
import kotlin.test.assertNotSame
8+
9+
class PrimitiveSerialDescriptorTest {
10+
11+
@Test
12+
fun testEqualsImplemented() {
13+
val first = PrimitiveSerialDescriptor("test_name", PrimitiveKind.LONG)
14+
val second = PrimitiveSerialDescriptor("test_name", PrimitiveKind.LONG)
15+
16+
assertNotSame(first, second)
17+
assertEquals(first, second)
18+
}
19+
20+
@Test
21+
fun testHashCodeStability() {
22+
val first = PrimitiveSerialDescriptor("test_name", PrimitiveKind.LONG)
23+
val second = PrimitiveSerialDescriptor("test_name", PrimitiveKind.LONG)
24+
25+
assertNotSame(first, second)
26+
assertEquals(first.hashCode(), second.hashCode())
27+
}
28+
29+
}

0 commit comments

Comments
 (0)