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 {
while (size < count) {
v = hmac.hash(k, v)
addAll(v.take(min(count - size, function.bytes)))
}
}.toUByteArray()

View File

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

View File

@@ -15,12 +15,33 @@ abstract class PRNG : Random() {
override fun nextBits(
bitCount: Int,
): Int {
if (bitCount !in 0..32) throw Exception()
if (bitCount == 0) return 0
if (bitCount !in 0..32)
throw IllegalArgumentException()
if (bitCount == 0)
return 0
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 {
fun LCG() = com.infendro.random.prng.LCG()
}