diff --git a/stateless/randutils.nim b/stateless/randutils.nim new file mode 100644 index 000000000..1c58da69f --- /dev/null +++ b/stateless/randutils.nim @@ -0,0 +1,59 @@ +import random, sets, nimcrypto/[utils, sysrand] + +type + RandGen*[T] = object + minVal, maxVal: T + + Bytes* = seq[byte] + +proc rng*[T](minVal, maxVal: T): RandGen[T] = + doAssert(minVal <= maxVal) + result.minVal = minVal + result.maxVal = maxVal + +proc rng*[T](minMax: T): RandGen[T] = + rng(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) + discard randomBytes(result[0].addr, len) + +proc randBytes*(len: int): Bytes = + result = newSeq[byte](len) + discard randomBytes(result[0].addr, len) + +proc randPrimitives*[T](val: int): T = + type + ByteLike = uint8 | byte | char + + when T is string: + randString(val) + elif T is int: + result = val + elif T is ByteLike: + result = T(val) + elif T is Bytes: + result = randBytes(val) + +proc randList*(T: typedesc, fillGen: RandGen, listLen: int, unique: static[bool] = true): seq[T] = + result = newSeqOfCap[T](listLen) + when unique: + var set = initHashSet[T]() + for len in 0.. 0: @@ -165,27 +212,10 @@ proc getBranchStack*(self: WitnessBuilder; key: openArray[byte]): string = raise newException(CorruptedTrieDatabase, "HexaryTrie node with an unexpected number of children") -#[ -proc hexPrefixDecode*(r: openArray[byte]): tuple[isLeaf: bool, nibbles: NibblesSeq] = - result.nibbles = initNibbleRange(r) - if r.len > 0: - result.isLeaf = (r[0] and 0x20) != 0 - let hasOddLen = (r[0] and 0x10) != 0 - result.nibbles.ibegin = 2 - int(hasOddLen) - else: - result.isLeaf = false - -proc sharedPrefixLen*(lhs, rhs: NibblesSeq): int = - result = 0 - while result < lhs.len and result < rhs.len: - if lhs[result] != rhs[result]: break - inc result -]# -proc getBranch*(self: WitnessBuilder; key: openArray[byte]): seq[seq[byte]] = +proc getBranch*(wb: WitnessBuilder; key: openArray[byte]): seq[seq[byte]] = var - node = self.db.get(self.root.data) + node = wb.db.get(wb.root.data) stack = @[(node, initNibbleRange(key))] - db = self.db result.add node while stack.len > 0: @@ -214,11 +244,10 @@ proc getBranch*(self: WitnessBuilder; key: openArray[byte]): seq[seq[byte]] = raise newException(CorruptedTrieDatabase, "HexaryTrie node with an unexpected number of children") -proc buildWitness*(self: var WitnessBuilder; key: openArray[byte]) = +proc buildWitness*(wb: var WitnessBuilder; key: openArray[byte]) = var - node = self.db.get(self.root.data) + node = wb.db.get(wb.root.data) stack = @[(node, initNibbleRange(key))] - db = self.db while stack.len > 0: let (node, path) = stack.pop() @@ -243,4 +272,3 @@ proc buildWitness*(self: var WitnessBuilder; key: openArray[byte]) = else: raise newException(CorruptedTrieDatabase, "HexaryTrie node with an unexpected number of children") -