Fixed JVM Serialization problems:

* EmptyCoroutineContext readResolve fixed
* CombinedContext.writeReplace serializes all context elements
This commit is contained in:
Roman Elizarov
2018-07-13 14:33:30 +03:00
committed by Denis Zharkov
parent e0f6165f10
commit 96b5bb1b31
@@ -22,7 +22,7 @@ public abstract class AbstractCoroutineContextElement(public override val key: K
@SinceKotlin("1.3") @SinceKotlin("1.3")
public object EmptyCoroutineContext : CoroutineContext, Serializable { public object EmptyCoroutineContext : CoroutineContext, Serializable {
private const val serialVersionUID: Long = 0 private const val serialVersionUID: Long = 0
private fun readResolve(): Any = this private fun readResolve(): Any = EmptyCoroutineContext
public override fun <E : Element> get(key: Key<E>): E? = null public override fun <E : Element> get(key: Key<E>): E? = null
public override fun <R> fold(initial: R, operation: (R, Element) -> R): R = initial public override fun <R> fold(initial: R, operation: (R, Element) -> R): R = initial
@@ -104,11 +104,13 @@ internal class CombinedContext(
} + "]" } + "]"
private fun writeReplace(): Any { private fun writeReplace(): Any {
val list = ArrayList<CoroutineContext>(size()) val n = size()
fold(Unit) { _, element -> val elements = arrayOfNulls<CoroutineContext>(n)
if (element is Serializable) list += element var index = 0
} fold(Unit) { _, element -> elements[index++] = element }
return Serialized(list.toTypedArray()) check(index == n)
@Suppress("UNCHECKED_CAST")
return Serialized(elements as Array<CoroutineContext>)
} }
private class Serialized(val elements: Array<CoroutineContext>) : Serializable { private class Serialized(val elements: Array<CoroutineContext>) : Serializable {