hashes.nim 18 KB

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