Make Random implementations serializable (KT-25571)
Make Random.Default, XorWowRandom, and wrapper classes for JDK Random implement Serializable interface. Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
This commit is contained in:
committed by
GitHub
parent
38967f208e
commit
00506a75d3
@@ -267,10 +267,17 @@ public abstract class Random {
|
||||
*
|
||||
* @sample samples.random.Randoms.defaultRandom
|
||||
*/
|
||||
companion object Default : Random() {
|
||||
|
||||
companion object Default : Random(), Serializable {
|
||||
private val defaultRandom: Random = defaultPlatformRandom()
|
||||
|
||||
private object Dummy : Serializable {
|
||||
private const val serialVersionUID = 0L
|
||||
|
||||
private fun readResolve(): Any = Random
|
||||
}
|
||||
|
||||
private fun writeReplace(): Any = Dummy
|
||||
|
||||
override fun nextBits(bitCount: Int): Int = defaultRandom.nextBits(bitCount)
|
||||
override fun nextInt(): Int = defaultRandom.nextInt()
|
||||
override fun nextInt(until: Int): Int = defaultRandom.nextInt(until)
|
||||
@@ -290,7 +297,8 @@ public abstract class Random {
|
||||
|
||||
override fun nextBytes(array: ByteArray): ByteArray = defaultRandom.nextBytes(array)
|
||||
override fun nextBytes(size: Int): ByteArray = defaultRandom.nextBytes(size)
|
||||
override fun nextBytes(array: ByteArray, fromIndex: Int, toIndex: Int): ByteArray = defaultRandom.nextBytes(array, fromIndex, toIndex)
|
||||
override fun nextBytes(array: ByteArray, fromIndex: Int, toIndex: Int): ByteArray =
|
||||
defaultRandom.nextBytes(array, fromIndex, toIndex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,7 +333,6 @@ public fun Random(seed: Int): Random = XorWowRandom(seed, seed.shr(31))
|
||||
public fun Random(seed: Long): Random = XorWowRandom(seed.toInt(), seed.shr(32).toInt())
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the next random `Int` from the random number generator in the specified [range].
|
||||
*
|
||||
|
||||
@@ -15,15 +15,14 @@ package kotlin.random
|
||||
* Available at https://www.jstatsoft.org/v08/i14/paper
|
||||
*
|
||||
*/
|
||||
internal class XorWowRandom
|
||||
internal constructor(
|
||||
internal class XorWowRandom internal constructor(
|
||||
private var x: Int,
|
||||
private var y: Int,
|
||||
private var z: Int,
|
||||
private var w: Int,
|
||||
private var v: Int,
|
||||
private var addend: Int
|
||||
) : Random() {
|
||||
) : Random(), Serializable {
|
||||
|
||||
internal constructor(seed1: Int, seed2: Int) :
|
||||
this(seed1, seed2, 0, 0, seed1.inv(), (seed1 shl 10) xor (seed2 ushr 4))
|
||||
@@ -53,4 +52,8 @@ internal constructor(
|
||||
|
||||
override fun nextBits(bitCount: Int): Int =
|
||||
nextInt().takeUpperBits(bitCount)
|
||||
|
||||
private companion object {
|
||||
private const val serialVersionUID: Long = 0L
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user