nim-eth/tests/trie/testutils.nim

79 lines
1.9 KiB
Nim
Raw Permalink Normal View History

2019-02-05 12:01:10 +00:00
import
std/[random, sets],
nimcrypto/[utils, sysrand]
2019-02-05 12:01:10 +00:00
type
RandGen*[T] = object
minVal, maxVal: T
KVPair* = ref object
key*: seq[byte]
value*: seq[byte]
2019-02-05 12:01:10 +00:00
proc randGen*[T](minVal, maxVal: T): RandGen[T] =
2019-03-13 22:15:26 +00:00
doAssert(minVal <= maxVal)
2019-02-05 12:01:10 +00:00
result.minVal = minVal
result.maxVal = maxVal
proc randGen*[T](minMax: T): RandGen[T] =
randGen(minMax, minMax)
proc getVal*[T](x: RandGen[T]): T =
if x.minVal == x.maxVal: return x.minVal
rand(x.minVal..x.maxVal)
proc randString*(len: int): string =
result = newString(len)
for i in 0..<len:
result[i] = rand(255).char
proc randBytes*(len: int): seq[byte] =
2019-02-18 04:02:26 +00:00
result = newSeq[byte](len)
2019-02-18 09:48:26 +00:00
discard randomBytes(result[0].addr, len)
2019-02-18 04:02:26 +00:00
proc toBytesRange*(str: string): seq[byte] =
2019-02-05 12:01:10 +00:00
var s: seq[byte]
if str[0] == '0' and str[1] == 'x':
s = fromHex(str.substr(2))
else:
s = newSeq[byte](str.len)
for i in 0 ..< str.len:
s[i] = byte(str[i])
result = s
2019-02-05 12:01:10 +00:00
proc randPrimitives*[T](val: int): T =
when T is string:
randString(val)
elif T is int:
result = val
elif T is string:
result = randString(val)
elif T is seq[byte]:
2019-02-18 04:02:26 +00:00
result = randBytes(val)
2019-02-05 12:01:10 +00:00
proc randList*(T: typedesc, strGen, listGen: RandGen, unique: bool = true): seq[T] =
let listLen = listGen.getVal()
result = newSeqOfCap[T](listLen)
if unique:
2020-04-18 08:17:59 +00:00
var set = initHashSet[T]()
2019-02-05 12:01:10 +00:00
for len in 0..<listLen:
while true:
let x = randPrimitives[T](strGen.getVal())
if x notin set:
result.add x
set.incl x
break
else:
for len in 0..<listLen:
let x = randPrimitives[T](strGen.getVal())
result.add x
proc randKVPair*(keySize = 32): seq[KVPair] =
const listLen = 100
let keys = randList(seq[byte], randGen(keySize, keySize), randGen(listLen, listLen))
let vals = randList(seq[byte], randGen(1, 100), randGen(listLen, listLen))
2019-02-05 12:01:10 +00:00
result = newSeq[KVPair](listLen)
for i in 0..<listLen:
result[i] = KVPair(key: keys[i], value: vals[i])