Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix memory leak caused by invalid KTypeWrapper's equals method #2274

Merged
merged 2 commits into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/jvmMain/src/kotlinx/serialization/internal/Caching.kt
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private class KTypeWrapper(private val origin: KType) : KType {

override fun equals(other: Any?): Boolean {
if (other == null) return false
if (origin != other) return false
if (origin != (other as? KTypeWrapper)?.origin) return false

val kClassifier = classifier
if (kClassifier is KClass<*>) {
Expand Down
53 changes: 53 additions & 0 deletions core/jvmTest/src/kotlinx/serialization/CachingTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization

import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.internal.StringSerializer
import kotlinx.serialization.internal.createCache
import kotlinx.serialization.internal.createParametrizedCache
import kotlinx.serialization.internal.kclass
import kotlinx.serialization.modules.*
import org.junit.Test
import kotlin.reflect.KClass
import kotlin.reflect.typeOf
import kotlin.test.*

class CachingTest {
@Test
fun testCache() {
var factoryCalled = 0

val cache = createCache {
factoryCalled += 1
it.serializerOrNull()
}

repeat(10) {
cache.get(typeOf<String>().kclass())
}

assertEquals(1, factoryCalled)
}

@Test
fun testParameterizedCache() {
var factoryCalled = 0

val cache = createParametrizedCache { clazz, types ->
factoryCalled += 1
val serializers = EmptySerializersModule().serializersForParameters(types, true)!!
clazz.parametrizedSerializerOrNull(types, serializers)
}

repeat(10) {
cache.get(typeOf<Map<*, *>>().kclass(), listOf(typeOf<String>(), typeOf<String>()))
}

assertEquals(1, factoryCalled)
}
}