hashes.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements efficient computations of hash values for diverse
  10. ## Nim types. All the procs are based on these two building blocks:
  11. ## - `!& proc <#!&,Hash,int>`_ used to start or mix a hash value, and
  12. ## - `!$ proc <#!$,Hash>`_ used to finish the hash value.
  13. ##
  14. ## If you want to implement hash procs for your custom types,
  15. ## you will end up writing the following kind of skeleton of code:
  16. runnableExamples:
  17. type
  18. Something = object
  19. foo: int
  20. bar: string
  21. iterator items(x: Something): Hash =
  22. yield hash(x.foo)
  23. yield hash(x.bar)
  24. proc hash(x: Something): Hash =
  25. ## Computes a Hash from `x`.
  26. var h: Hash = 0
  27. # Iterate over parts of `x`.
  28. for xAtom in x:
  29. # Mix the atom with the partial hash.
  30. h = h !& xAtom
  31. # Finish the hash.
  32. result = !$h
  33. ## If your custom types contain fields for which there already is a `hash` proc,
  34. ## you can simply hash together the hash values of the individual fields:
  35. runnableExamples:
  36. type
  37. Something = object
  38. foo: int
  39. bar: string
  40. proc hash(x: Something): Hash =
  41. ## Computes a Hash from `x`.
  42. var h: Hash = 0
  43. h = h !& hash(x.foo)
  44. h = h !& hash(x.bar)
  45. result = !$h
  46. ## .. important:: Use `-d:nimPreviewHashRef` to
  47. ## enable hashing `ref`s. It is expected that this behavior
  48. ## becomes the new default in upcoming versions.
  49. ##
  50. ## .. note:: If the type has a `==` operator, the following must hold:
  51. ## If two values compare equal, their hashes must also be equal.
  52. ##
  53. ## See also
  54. ## ========
  55. ## * `md5 module <md5.html>`_ for the MD5 checksum algorithm
  56. ## * `base64 module <base64.html>`_ for a Base64 encoder and decoder
  57. ## * `std/sha1 module <sha1.html>`_ for a SHA-1 encoder and decoder
  58. ## * `tables module <tables.html>`_ for hash tables
  59. import std/private/since
  60. type
  61. Hash* = int ## A hash value. Hash tables using these values should
  62. ## always have a size of a power of two so they can use the `and`
  63. ## operator instead of `mod` for truncation of the hash value.
  64. proc `!&`*(h: Hash, val: int): Hash {.inline.} =
  65. ## Mixes a hash value `h` with `val` to produce a new hash value.
  66. ##
  67. ## This is only needed if you need to implement a `hash` proc for a new datatype.
  68. let h = cast[uint](h)
  69. let val = cast[uint](val)
  70. var res = h + val
  71. res = res + res shl 10
  72. res = res xor (res shr 6)
  73. result = cast[Hash](res)
  74. proc `!$`*(h: Hash): Hash {.inline.} =
  75. ## Finishes the computation of the hash value.
  76. ##
  77. ## This is only needed if you need to implement a `hash` proc for a new datatype.
  78. let h = cast[uint](h) # Hash is practically unsigned.
  79. var res = h + h shl 3
  80. res = res xor (res shr 11)
  81. res = res + res shl 15
  82. result = cast[Hash](res)
  83. proc hiXorLoFallback64(a, b: uint64): uint64 {.inline.} =
  84. let # Fall back in 64-bit arithmetic
  85. aH = a shr 32
  86. aL = a and 0xFFFFFFFF'u64
  87. bH = b shr 32
  88. bL = b and 0xFFFFFFFF'u64
  89. rHH = aH * bH
  90. rHL = aH * bL
  91. rLH = aL * bH
  92. rLL = aL * bL
  93. t = rLL + (rHL shl 32)
  94. var c = if t < rLL: 1'u64 else: 0'u64
  95. let lo = t + (rLH shl 32)
  96. c += (if lo < t: 1'u64 else: 0'u64)
  97. let hi = rHH + (rHL shr 32) + (rLH shr 32) + c
  98. return hi xor lo
  99. proc hiXorLo(a, b: uint64): uint64 {.inline.} =
  100. # XOR of the high & low 8 bytes of the full 16 byte product.
  101. when nimvm:
  102. result = hiXorLoFallback64(a, b) # `result =` is necessary here.
  103. else:
  104. when Hash.sizeof < 8:
  105. result = hiXorLoFallback64(a, b)
  106. elif defined(gcc) or defined(llvm_gcc) or defined(clang):
  107. {.emit: """__uint128_t r = `a`; r *= `b`; `result` = (r >> 64) ^ r;""".}
  108. elif defined(windows) and not defined(tcc):
  109. proc umul128(a, b: uint64, c: ptr uint64): uint64 {.importc: "_umul128", header: "intrin.h".}
  110. var b = b
  111. let c = umul128(a, b, addr b)
  112. result = c xor b
  113. else:
  114. result = hiXorLoFallback64(a, b)
  115. when defined(js):
  116. import std/jsbigints
  117. import std/private/jsutils
  118. proc hiXorLoJs(a, b: JsBigInt): JsBigInt =
  119. let
  120. prod = a * b
  121. mask = big"0xffffffffffffffff" # (big"1" shl big"64") - big"1"
  122. result = (prod shr big"64") xor (prod and mask)
  123. template hashWangYiJS(x: JsBigInt): Hash =
  124. let
  125. P0 = big"0xa0761d6478bd642f"
  126. P1 = big"0xe7037ed1a0b428db"
  127. P58 = big"0xeb44accab455d16d" # big"0xeb44accab455d165" xor big"8"
  128. res = hiXorLoJs(hiXorLoJs(P0, x xor P1), P58)
  129. cast[Hash](toNumber(wrapToInt(res, 32)))
  130. template toBits(num: float): JsBigInt =
  131. let
  132. x = newArrayBuffer(8)
  133. y = newFloat64Array(x)
  134. if hasBigUint64Array():
  135. let z = newBigUint64Array(x)
  136. y[0] = num
  137. z[0]
  138. else:
  139. let z = newUint32Array(x)
  140. y[0] = num
  141. big(z[0]) + big(z[1]) shl big(32)
  142. proc hashWangYi1*(x: int64|uint64|Hash): Hash {.inline.} =
  143. ## Wang Yi's hash_v1 for 64-bit ints (see https://github.com/rurban/smhasher for
  144. ## more details). This passed all scrambling tests in Spring 2019 and is simple.
  145. ##
  146. ## **Note:** It's ok to define `proc(x: int16): Hash = hashWangYi1(Hash(x))`.
  147. const P0 = 0xa0761d6478bd642f'u64
  148. const P1 = 0xe7037ed1a0b428db'u64
  149. const P58 = 0xeb44accab455d165'u64 xor 8'u64
  150. template h(x): untyped = hiXorLo(hiXorLo(P0, uint64(x) xor P1), P58)
  151. when nimvm:
  152. when defined(js): # Nim int64<->JS Number & VM match => JS gets 32-bit hash
  153. result = cast[Hash](h(x)) and cast[Hash](0xFFFFFFFF)
  154. else:
  155. result = cast[Hash](h(x))
  156. else:
  157. when defined(js):
  158. if hasJsBigInt():
  159. result = hashWangYiJS(big(x))
  160. else:
  161. result = cast[Hash](x) and cast[Hash](0xFFFFFFFF)
  162. else:
  163. result = cast[Hash](h(x))
  164. proc hashData*(data: pointer, size: int): Hash =
  165. ## Hashes an array of bytes of size `size`.
  166. var h: Hash = 0
  167. when defined(js):
  168. var p: cstring
  169. asm """`p` = `Data`"""
  170. else:
  171. var p = cast[cstring](data)
  172. var i = 0
  173. var s = size
  174. while s > 0:
  175. h = h !& ord(p[i])
  176. inc(i)
  177. dec(s)
  178. result = !$h
  179. proc hashIdentity*[T: Ordinal|enum](x: T): Hash {.inline, since: (1, 3).} =
  180. ## The identity hash, i.e. `hashIdentity(x) = x`.
  181. cast[Hash](ord(x))
  182. when defined(nimIntHash1):
  183. proc hash*[T: Ordinal|enum](x: T): Hash {.inline.} =
  184. ## Efficient hashing of integers.
  185. cast[Hash](ord(x))
  186. else:
  187. proc hash*[T: Ordinal|enum](x: T): Hash {.inline.} =
  188. ## Efficient hashing of integers.
  189. hashWangYi1(uint64(ord(x)))
  190. when defined(js):
  191. var objectID = 0
  192. proc getObjectId(x: pointer): int =
  193. asm """
  194. if (typeof `x` == "object") {
  195. if ("_NimID" in `x`)
  196. `result` = `x`["_NimID"];
  197. else {
  198. `result` = ++`objectID`;
  199. `x`["_NimID"] = `result`;
  200. }
  201. }
  202. """
  203. proc hash*(x: pointer): Hash {.inline.} =
  204. ## Efficient `hash` overload.
  205. when defined(js):
  206. let y = getObjectId(x)
  207. else:
  208. let y = cast[int](x)
  209. hash(y) # consistent with code expecting scrambled hashes depending on `nimIntHash1`.
  210. proc hash*[T](x: ptr[T]): Hash {.inline.} =
  211. ## Efficient `hash` overload.
  212. runnableExamples:
  213. var a: array[10, uint8]
  214. assert a[0].addr.hash != a[1].addr.hash
  215. assert cast[pointer](a[0].addr).hash == a[0].addr.hash
  216. hash(cast[pointer](x))
  217. when defined(nimPreviewHashRef) or defined(nimdoc):
  218. proc hash*[T](x: ref[T]): Hash {.inline.} =
  219. ## Efficient `hash` overload.
  220. ##
  221. ## .. important:: Use `-d:nimPreviewHashRef` to
  222. ## enable hashing `ref`s. It is expected that this behavior
  223. ## becomes the new default in upcoming versions.
  224. runnableExamples("-d:nimPreviewHashRef"):
  225. type A = ref object
  226. x: int
  227. let a = A(x: 3)
  228. let ha = a.hash
  229. assert ha != A(x: 3).hash # A(x: 3) is a different ref object from `a`.
  230. a.x = 4
  231. assert ha == a.hash # the hash only depends on the address
  232. runnableExamples("-d:nimPreviewHashRef"):
  233. # you can overload `hash` if you want to customize semantics
  234. type A[T] = ref object
  235. x, y: T
  236. proc hash(a: A): Hash = hash(a.x)
  237. assert A[int](x: 3, y: 4).hash == A[int](x: 3, y: 5).hash
  238. # xxx pending bug #17733, merge as `proc hash*(pointer | ref | ptr): Hash`
  239. # or `proc hash*[T: ref | ptr](x: T): Hash`
  240. hash(cast[pointer](x))
  241. proc hash*(x: float): Hash {.inline.} =
  242. ## Efficient hashing of floats.
  243. let y = x + 0.0 # for denormalization
  244. when nimvm:
  245. # workaround a JS VM bug: bug #16547
  246. result = hashWangYi1(cast[int64](float64(y)))
  247. else:
  248. when not defined(js):
  249. result = hashWangYi1(cast[Hash](y))
  250. else:
  251. result = hashWangYiJS(toBits(y))
  252. # Forward declarations before methods that hash containers. This allows
  253. # containers to contain other containers
  254. proc hash*[A](x: openArray[A]): Hash
  255. proc hash*[A](x: set[A]): Hash
  256. when defined(js):
  257. proc imul(a, b: uint32): uint32 =
  258. # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
  259. let mask = 0xffff'u32
  260. var
  261. aHi = (a shr 16) and mask
  262. aLo = a and mask
  263. bHi = (b shr 16) and mask
  264. bLo = b and mask
  265. result = (aLo * bLo) + (aHi * bLo + aLo * bHi) shl 16
  266. else:
  267. template imul(a, b: uint32): untyped = a * b
  268. proc rotl32(x: uint32, r: int): uint32 {.inline.} =
  269. (x shl r) or (x shr (32 - r))
  270. proc murmurHash(x: openArray[byte]): Hash =
  271. # https://github.com/PeterScott/murmur3/blob/master/murmur3.c
  272. const
  273. c1 = 0xcc9e2d51'u32
  274. c2 = 0x1b873593'u32
  275. n1 = 0xe6546b64'u32
  276. m1 = 0x85ebca6b'u32
  277. m2 = 0xc2b2ae35'u32
  278. let
  279. size = len(x)
  280. stepSize = 4 # 32-bit
  281. n = size div stepSize
  282. var
  283. h1: uint32
  284. i = 0
  285. template impl =
  286. var j = stepSize
  287. while j > 0:
  288. dec j
  289. k1 = (k1 shl 8) or (ord(x[i+j])).uint32
  290. # body
  291. while i < n * stepSize:
  292. var k1: uint32
  293. when nimvm:
  294. impl()
  295. else:
  296. when declared(copyMem):
  297. copyMem(unsafeAddr k1, unsafeAddr x[i], 4)
  298. else:
  299. impl()
  300. inc i, stepSize
  301. k1 = imul(k1, c1)
  302. k1 = rotl32(k1, 15)
  303. k1 = imul(k1, c2)
  304. h1 = h1 xor k1
  305. h1 = rotl32(h1, 13)
  306. h1 = h1*5 + n1
  307. # tail
  308. var k1: uint32
  309. var rem = size mod stepSize
  310. while rem > 0:
  311. dec rem
  312. k1 = (k1 shl 8) or (ord(x[i+rem])).uint32
  313. k1 = imul(k1, c1)
  314. k1 = rotl32(k1, 15)
  315. k1 = imul(k1, c2)
  316. h1 = h1 xor k1
  317. # finalization
  318. h1 = h1 xor size.uint32
  319. h1 = h1 xor (h1 shr 16)
  320. h1 = imul(h1, m1)
  321. h1 = h1 xor (h1 shr 13)
  322. h1 = imul(h1, m2)
  323. h1 = h1 xor (h1 shr 16)
  324. return cast[Hash](h1)
  325. proc hashVmImpl(x: cstring, sPos, ePos: int): Hash =
  326. doAssert false, "implementation override in compiler/vmops.nim"
  327. proc hashVmImpl(x: string, sPos, ePos: int): Hash =
  328. doAssert false, "implementation override in compiler/vmops.nim"
  329. proc hashVmImplChar(x: openArray[char], sPos, ePos: int): Hash =
  330. doAssert false, "implementation override in compiler/vmops.nim"
  331. proc hashVmImplByte(x: openArray[byte], sPos, ePos: int): Hash =
  332. doAssert false, "implementation override in compiler/vmops.nim"
  333. proc hash*(x: string): Hash =
  334. ## Efficient hashing of strings.
  335. ##
  336. ## **See also:**
  337. ## * `hashIgnoreStyle <#hashIgnoreStyle,string>`_
  338. ## * `hashIgnoreCase <#hashIgnoreCase,string>`_
  339. runnableExamples:
  340. doAssert hash("abracadabra") != hash("AbracadabrA")
  341. when not defined(nimToOpenArrayCString):
  342. result = 0
  343. for c in x:
  344. result = result !& ord(c)
  345. result = !$result
  346. else:
  347. when nimvm:
  348. result = hashVmImpl(x, 0, high(x))
  349. else:
  350. result = murmurHash(toOpenArrayByte(x, 0, high(x)))
  351. proc hash*(x: cstring): Hash =
  352. ## Efficient hashing of null-terminated strings.
  353. runnableExamples:
  354. doAssert hash(cstring"abracadabra") == hash("abracadabra")
  355. doAssert hash(cstring"AbracadabrA") == hash("AbracadabrA")
  356. doAssert hash(cstring"abracadabra") != hash(cstring"AbracadabrA")
  357. when not defined(nimToOpenArrayCString):
  358. result = 0
  359. var i = 0
  360. while x[i] != '\0':
  361. result = result !& ord(x[i])
  362. inc i
  363. result = !$result
  364. else:
  365. when nimvm:
  366. hashVmImpl(x, 0, high(x))
  367. else:
  368. when not defined(js) and defined(nimToOpenArrayCString):
  369. murmurHash(toOpenArrayByte(x, 0, x.high))
  370. else:
  371. let xx = $x
  372. murmurHash(toOpenArrayByte(xx, 0, high(xx)))
  373. proc hash*(sBuf: string, sPos, ePos: int): Hash =
  374. ## Efficient hashing of a string buffer, from starting
  375. ## position `sPos` to ending position `ePos` (included).
  376. ##
  377. ## `hash(myStr, 0, myStr.high)` is equivalent to `hash(myStr)`.
  378. runnableExamples:
  379. var a = "abracadabra"
  380. doAssert hash(a, 0, 3) == hash(a, 7, 10)
  381. when not defined(nimToOpenArrayCString):
  382. result = 0
  383. for i in sPos..ePos:
  384. result = result !& ord(sBuf[i])
  385. result = !$result
  386. else:
  387. murmurHash(toOpenArrayByte(sBuf, sPos, ePos))
  388. proc hashIgnoreStyle*(x: string): Hash =
  389. ## Efficient hashing of strings; style is ignored.
  390. ##
  391. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  392. ##
  393. ## **See also:**
  394. ## * `hashIgnoreCase <#hashIgnoreCase,string>`_
  395. runnableExamples:
  396. doAssert hashIgnoreStyle("aBr_aCa_dAB_ra") == hashIgnoreStyle("abracadabra")
  397. doAssert hashIgnoreStyle("abcdefghi") != hash("abcdefghi")
  398. var h: Hash = 0
  399. var i = 0
  400. let xLen = x.len
  401. while i < xLen:
  402. var c = x[i]
  403. if c == '_':
  404. inc(i)
  405. else:
  406. if c in {'A'..'Z'}:
  407. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  408. h = h !& ord(c)
  409. inc(i)
  410. result = !$h
  411. proc hashIgnoreStyle*(sBuf: string, sPos, ePos: int): Hash =
  412. ## Efficient hashing of a string buffer, from starting
  413. ## position `sPos` to ending position `ePos` (included); style is ignored.
  414. ##
  415. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  416. ##
  417. ## `hashIgnoreStyle(myBuf, 0, myBuf.high)` is equivalent
  418. ## to `hashIgnoreStyle(myBuf)`.
  419. runnableExamples:
  420. var a = "ABracada_b_r_a"
  421. doAssert hashIgnoreStyle(a, 0, 3) == hashIgnoreStyle(a, 7, a.high)
  422. var h: Hash = 0
  423. var i = sPos
  424. while i <= ePos:
  425. var c = sBuf[i]
  426. if c == '_':
  427. inc(i)
  428. else:
  429. if c in {'A'..'Z'}:
  430. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  431. h = h !& ord(c)
  432. inc(i)
  433. result = !$h
  434. proc hashIgnoreCase*(x: string): Hash =
  435. ## Efficient hashing of strings; case is ignored.
  436. ##
  437. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  438. ##
  439. ## **See also:**
  440. ## * `hashIgnoreStyle <#hashIgnoreStyle,string>`_
  441. runnableExamples:
  442. doAssert hashIgnoreCase("ABRAcaDABRA") == hashIgnoreCase("abRACAdabra")
  443. doAssert hashIgnoreCase("abcdefghi") != hash("abcdefghi")
  444. var h: Hash = 0
  445. for i in 0..x.len-1:
  446. var c = x[i]
  447. if c in {'A'..'Z'}:
  448. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  449. h = h !& ord(c)
  450. result = !$h
  451. proc hashIgnoreCase*(sBuf: string, sPos, ePos: int): Hash =
  452. ## Efficient hashing of a string buffer, from starting
  453. ## position `sPos` to ending position `ePos` (included); case is ignored.
  454. ##
  455. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  456. ##
  457. ## `hashIgnoreCase(myBuf, 0, myBuf.high)` is equivalent
  458. ## to `hashIgnoreCase(myBuf)`.
  459. runnableExamples:
  460. var a = "ABracadabRA"
  461. doAssert hashIgnoreCase(a, 0, 3) == hashIgnoreCase(a, 7, 10)
  462. var h: Hash = 0
  463. for i in sPos..ePos:
  464. var c = sBuf[i]
  465. if c in {'A'..'Z'}:
  466. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  467. h = h !& ord(c)
  468. result = !$h
  469. proc hash*[T: tuple | object | proc](x: T): Hash =
  470. ## Efficient `hash` overload.
  471. runnableExamples:
  472. # for `tuple|object`, `hash` must be defined for each component of `x`.
  473. type Obj = object
  474. x: int
  475. y: string
  476. type Obj2[T] = object
  477. x: int
  478. y: string
  479. assert hash(Obj(x: 520, y: "Nim")) != hash(Obj(x: 520, y: "Nim2"))
  480. # you can define custom hashes for objects (even if they're generic):
  481. proc hash(a: Obj2): Hash = hash((a.x))
  482. assert hash(Obj2[float](x: 520, y: "Nim")) == hash(Obj2[float](x: 520, y: "Nim2"))
  483. runnableExamples:
  484. # proc
  485. proc fn1() = discard
  486. const fn1b = fn1
  487. assert hash(fn1b) == hash(fn1)
  488. # closure
  489. proc outer =
  490. var a = 0
  491. proc fn2() = a.inc
  492. assert fn2 is "closure"
  493. let fn2b = fn2
  494. assert hash(fn2b) == hash(fn2)
  495. assert hash(fn2) != hash(fn1)
  496. outer()
  497. when T is "closure":
  498. result = hash((rawProc(x), rawEnv(x)))
  499. elif T is (proc):
  500. result = hash(pointer(x))
  501. else:
  502. for f in fields(x):
  503. result = result !& hash(f)
  504. result = !$result
  505. proc hash*[A](x: openArray[A]): Hash =
  506. ## Efficient hashing of arrays and sequences.
  507. ## There must be a `hash` proc defined for the element type `A`.
  508. when A is byte:
  509. result = murmurHash(x)
  510. elif A is char:
  511. when nimvm:
  512. result = hashVmImplChar(x, 0, x.high)
  513. else:
  514. result = murmurHash(toOpenArrayByte(x, 0, x.high))
  515. else:
  516. for a in x:
  517. result = result !& hash(a)
  518. result = !$result
  519. proc hash*[A](aBuf: openArray[A], sPos, ePos: int): Hash =
  520. ## Efficient hashing of portions of arrays and sequences, from starting
  521. ## position `sPos` to ending position `ePos` (included).
  522. ## There must be a `hash` proc defined for the element type `A`.
  523. ##
  524. ## `hash(myBuf, 0, myBuf.high)` is equivalent to `hash(myBuf)`.
  525. runnableExamples:
  526. let a = [1, 2, 5, 1, 2, 6]
  527. doAssert hash(a, 0, 1) == hash(a, 3, 4)
  528. when A is byte:
  529. when nimvm:
  530. result = hashVmImplByte(aBuf, sPos, ePos)
  531. else:
  532. result = murmurHash(toOpenArray(aBuf, sPos, ePos))
  533. elif A is char:
  534. when nimvm:
  535. result = hashVmImplChar(aBuf, sPos, ePos)
  536. else:
  537. result = murmurHash(toOpenArrayByte(aBuf, sPos, ePos))
  538. else:
  539. for i in sPos .. ePos:
  540. result = result !& hash(aBuf[i])
  541. result = !$result
  542. proc hash*[A](x: set[A]): Hash =
  543. ## Efficient hashing of sets.
  544. ## There must be a `hash` proc defined for the element type `A`.
  545. for it in items(x):
  546. result = result !& hash(it)
  547. result = !$result