Skip to content

Commit

Permalink
Define a hash function in order to support Stint keys in hash tables (#…
Browse files Browse the repository at this point in the history
…102)

* Hash stint values as byte blobs; Add a basic test for using stint keys in a table
  • Loading branch information
zah authored and arnetheduck committed Dec 18, 2019
1 parent f0da040 commit 9e49b00
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
9 changes: 8 additions & 1 deletion stint/io.nim
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import
./private/int_negabs,
./private/compiletime_helpers,
./intops,
typetraits, algorithm
typetraits, algorithm, hashes

template static_check_size(T: typedesc[SomeInteger], bits: static[int]) =
# To avoid a costly runtime check, we refuse storing into StUint types smaller
Expand Down Expand Up @@ -512,3 +512,10 @@ func toByteArrayBE*[bits: static[int]](n: StUint[bits]): array[bits div 8, byte]
let n_ptr {.restrict.} = cast[ptr array[N, byte]](n.unsafeAddr)
for i in 0 ..< N:
result[N-1 - i] = n_ptr[i]

template hash*(num: StUint|StInt): Hash =
# TODO:
# `hashData` is not particularly efficient.
# Explore better hashing solutions in nim-stew.
hashData(unsafeAddr num, sizeof num)

36 changes: 35 additions & 1 deletion tests/test_io.nim
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# at your option. This file may not be copied, modified, or distributed except according to those terms.

import ../stint, unittest, strutils, math, test_helpers
import ../stint, unittest, strutils, math, test_helpers, tables

template nativeStuint(chk, nint: untyped, bits: int) =
chk $(nint.stuint(bits)) == $(nint)
Expand Down Expand Up @@ -1314,4 +1314,38 @@ proc main() =
check: eve.raw_sig.r.parse(Stuint[256], 16) == "84467545608142925331782333363288012579669270632210954476013542647119929595395".u256
check: eve.raw_sig.s.parse(Stuint[256], 16) == "43529886636775750164425297556346136250671451061152161143648812009114516499167".u256

test "Using stint values in a hash table":
block:
var t = initTable[UInt128, string]()

var numbers = @[
parse("0", UInt128),
parse("122342408432", UInt128),
parse("23853895230124238754328", UInt128),
parse("4539086493082871342142388475734534753453", UInt128),
]

for n in numbers:
t[n] = $n

for n in numbers:
check t[n] == $n

block:
var t = initTable[Int256, string]()

var numbers = @[
parse("0", Int256),
parse("-1", Int256),
parse("-12315123298", Int256),
parse("23853895230124238754328", Int256),
parse("-3429023852897428742874325245342129842", Int256),
]

for n in numbers:
t[n] = $n

for n in numbers:
check t[n] == $n

main()

0 comments on commit 9e49b00

Please sign in to comment.