optimize nextBytes()

This commit is contained in:
2025-12-13 23:51:08 +01:00
parent 3effa09602
commit d4be1689e2
3 changed files with 23 additions and 4 deletions

View File

@@ -35,7 +35,6 @@ class HMAC internal constructor(
val bytes = buildList { val bytes = buildList {
while (size < count) { while (size < count) {
v = hmac.hash(k, v) v = hmac.hash(k, v)
addAll(v.take(min(count - size, function.bytes))) addAll(v.take(min(count - size, function.bytes)))
} }
}.toUByteArray() }.toUByteArray()

View File

@@ -26,7 +26,6 @@ class LCG internal constructor() : PRNG() {
return buildList { return buildList {
while (size < count) { while (size < count) {
x = (a * x + c) % m x = (a * x + c) % m
addAll(x.toUByteArray().takeLast(min(count - size, 6))) addAll(x.toUByteArray().takeLast(min(count - size, 6)))
} }
}.toUByteArray() }.toUByteArray()

View File

@@ -15,12 +15,33 @@ abstract class PRNG : Random() {
override fun nextBits( override fun nextBits(
bitCount: Int, bitCount: Int,
): Int { ): Int {
if (bitCount !in 0..32) throw Exception() if (bitCount !in 0..32)
if (bitCount == 0) return 0 throw IllegalArgumentException()
if (bitCount == 0)
return 0
return generate(4).toInt() ushr (32 - bitCount) return generate(4).toInt() ushr (32 - bitCount)
} }
override fun nextBytes(
array: ByteArray,
fromIndex: Int,
toIndex: Int,
): ByteArray {
if (fromIndex !in 0..array.size || toIndex !in 0..array.size)
throw IllegalArgumentException()
if (fromIndex > toIndex)
throw IllegalArgumentException()
val size = toIndex - fromIndex
val bytes = generate(size).asByteArray()
for (i in 0..<size) {
array[i + fromIndex] = bytes[i]
}
return array
}
companion object { companion object {
fun LCG() = com.infendro.random.prng.LCG() fun LCG() = com.infendro.random.prng.LCG()
} }