From d6b0dad73eceae682dd2acc4e5eb005d26dff149 Mon Sep 17 00:00:00 2001 From: andri lim Date: Sat, 16 Jun 2018 18:46:02 +0700 Subject: [PATCH] add hash function --- ranges/typedranges.nim | 10 +++++++++- tests/ttypedranges.nim | 10 +++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/ranges/typedranges.nim b/ranges/typedranges.nim index c879b30..743907b 100644 --- a/ranges/typedranges.nim +++ b/ranges/typedranges.nim @@ -1,4 +1,4 @@ -import ./ptr_arith, typetraits +import ./ptr_arith, typetraits, hashes const rangesGCHoldEnabled = not defined(rangesDisableGCHold) const unsafeAPIEnabled = defined(rangesEnableUnsafeAPI) @@ -50,6 +50,14 @@ proc toRange*[T](a: seq[T]): Range[T] {.inline.} = toImmutableRange(a) converter toImmutableRange*[T](a: MutRange[T]): Range[T] {.inline.} = Range[T](a) +proc hash*(x: Range): Hash = + var h: Hash = 0 + when rangesGCHoldEnabled: + h = h !& hash(x.gcHold) + h = h !& hash(x.start) + h = h !& hash(x.mLen) + result = !$h + proc len*(r: Range): int {.inline.} = int(r.mLen) proc high*(r: Range): int {.inline.} = r.len - 1 diff --git a/tests/ttypedranges.nim b/tests/ttypedranges.nim index e009909..9fc0af8 100644 --- a/tests/ttypedranges.nim +++ b/tests/ttypedranges.nim @@ -1,5 +1,5 @@ import - unittest, + unittest, sets, ../ranges/typedranges suite "Typed ranges": @@ -71,3 +71,11 @@ suite "Typed ranges": # check(r[0] == 5) # XXX: Uncomment once nim bug #8044 is fixed r[1] = 10 check(r2[1] == 10) + + test "hash function": + var a = toRange(@[1,2,3]) + var b = toRange(@[4,5,6]) + var c = toRange(@[7,8,9]) + var x = toSet([a, b, c, a, b]) + check x.len == 3 + check a in x