implement optimizations
This commit is contained in:
@@ -1,33 +1,23 @@
|
||||
package com.infendro.random.prng
|
||||
|
||||
import com.infendro.bytearray.padStart
|
||||
import com.infendro.bytearray.toUByteArray
|
||||
import com.infendro.bytearray.toULong
|
||||
import kotlin.math.min
|
||||
import kotlin.properties.Delegates
|
||||
import com.infendro.bytes.bytearray.toLong
|
||||
import com.infendro.hash.sha2.`SHA-256`
|
||||
import com.infendro.random.PRNG
|
||||
import kotlin.properties.Delegates.notNull
|
||||
|
||||
class LCG internal constructor() : PRNG() {
|
||||
private val a: ULong = 25214903917UL
|
||||
private val c: ULong = 11UL
|
||||
private val m: ULong = 1UL shl 48
|
||||
private val a: Long = 25214903917L
|
||||
private val c: Long = 11L
|
||||
private val mask: Long = (1L shl 48) - 1
|
||||
|
||||
private var x: ULong by Delegates.notNull()
|
||||
private var x: Long by notNull()
|
||||
|
||||
override fun seed(
|
||||
seed: UByteArray,
|
||||
) {
|
||||
val s = seed.padStart(8, 0x00U).takeLast(8).toUByteArray()
|
||||
x = s.toULong() % m
|
||||
override fun seed(seed: ByteArray) {
|
||||
x = `SHA-256`.hash(seed).toLong() and mask
|
||||
}
|
||||
|
||||
override fun generate(
|
||||
count: Int,
|
||||
): UByteArray {
|
||||
return buildList {
|
||||
while (size < count) {
|
||||
x = (a * x + c) % m
|
||||
addAll(x.toUByteArray().takeLast(min(count - size, 6)))
|
||||
}
|
||||
}.toUByteArray()
|
||||
override fun generate(): Int {
|
||||
x = (a * x + c) and mask
|
||||
return (x ushr 16).toInt()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user