nim-eth/tests/trie/testutils.nim

92 lines
2.3 KiB
Nim
Raw Normal View History

2019-02-05 12:01:10 +00:00
import
random, sets, eth/trie/trie_utils as ethUtils,
2019-02-18 09:48:26 +00:00
eth/rlp/types as rlpTypes, ranges/bitranges,
nimcrypto/[utils, sysrand]
2019-02-05 12:01:10 +00:00
type
RandGen*[T] = object
minVal, maxVal: T
KVPair* = ref object
key*: string
value*: string
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
2019-02-18 04:02:26 +00:00
proc randBytes*(len: int): Bytes =
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
2019-02-05 12:01:10 +00:00
proc toBytesRange*(str: string): BytesRange =
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.toRange
proc randPrimitives*[T](val: int): T =
when T is string:
randString(val)
elif T is int:
result = val
elif T is BytesRange:
result = randString(val).toRange
2019-02-18 04:02:26 +00:00
elif T is Bytes:
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:
var set = initSet[T]()
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(string, randGen(keySize, keySize), randGen(listLen, listLen))
let vals = randList(string, randGen(1, 100), randGen(listLen, listLen))
result = newSeq[KVPair](listLen)
for i in 0..<listLen:
result[i] = KVPair(key: keys[i], value: vals[i])
proc toBytes*(str: string): Bytes =
result = newSeq[byte](str.len)
for i in 0..<str.len:
result[i] = byte(str[i])
proc genBitVec*(len: int): BitRange =
let k = ((len + 7) and (not 7)) shr 3
var s = newSeq[byte](k)
result = bits(s, len)
for i in 0..<len:
result[i] = rand(2) == 1