hashes.nim 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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. ## * `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. {.emit: """`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. {.emit: """
  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. template impl =
  288. var j = stepSize
  289. while j > 0:
  290. dec j
  291. k1 = (k1 shl 8) or (ord(x[i+j])).uint32
  292. # body
  293. while i < n * stepSize:
  294. var k1: uint32
  295. when nimvm:
  296. impl()
  297. else:
  298. when declared(copyMem):
  299. copyMem(addr k1, addr x[i], 4)
  300. else:
  301. impl()
  302. inc i, stepSize
  303. k1 = imul(k1, c1)
  304. k1 = rotl32(k1, 15)
  305. k1 = imul(k1, c2)
  306. h1 = h1 xor k1
  307. h1 = rotl32(h1, 13)
  308. h1 = h1*5 + n1
  309. # tail
  310. var k1: uint32
  311. var rem = size mod stepSize
  312. while rem > 0:
  313. dec rem
  314. k1 = (k1 shl 8) or (ord(x[i+rem])).uint32
  315. k1 = imul(k1, c1)
  316. k1 = rotl32(k1, 15)
  317. k1 = imul(k1, c2)
  318. h1 = h1 xor k1
  319. # finalization
  320. h1 = h1 xor size.uint32
  321. h1 = h1 xor (h1 shr 16)
  322. h1 = imul(h1, m1)
  323. h1 = h1 xor (h1 shr 13)
  324. h1 = imul(h1, m2)
  325. h1 = h1 xor (h1 shr 16)
  326. return cast[Hash](h1)
  327. proc hashVmImpl(x: cstring, sPos, ePos: int): Hash =
  328. raiseAssert "implementation override in compiler/vmops.nim"
  329. proc hashVmImpl(x: string, sPos, ePos: int): Hash =
  330. raiseAssert "implementation override in compiler/vmops.nim"
  331. proc hashVmImplChar(x: openArray[char], sPos, ePos: int): Hash =
  332. raiseAssert "implementation override in compiler/vmops.nim"
  333. proc hashVmImplByte(x: openArray[byte], sPos, ePos: int): Hash =
  334. raiseAssert "implementation override in compiler/vmops.nim"
  335. const k0 = 0xc3a5c85c97cb3127u64 # Primes on (2^63, 2^64) for various uses
  336. const k1 = 0xb492b66fbe98f273u64
  337. const k2 = 0x9ae16a3b2f90404fu64
  338. proc load4e(s: openArray[byte], o=0): uint32 {.inline.} =
  339. uint32(s[o + 3]) shl 24 or uint32(s[o + 2]) shl 16 or
  340. uint32(s[o + 1]) shl 8 or uint32(s[o + 0])
  341. proc load8e(s: openArray[byte], o=0): uint64 {.inline.} =
  342. uint64(s[o + 7]) shl 56 or uint64(s[o + 6]) shl 48 or
  343. uint64(s[o + 5]) shl 40 or uint64(s[o + 4]) shl 32 or
  344. uint64(s[o + 3]) shl 24 or uint64(s[o + 2]) shl 16 or
  345. uint64(s[o + 1]) shl 8 or uint64(s[o + 0])
  346. proc load4(s: openArray[byte], o=0): uint32 {.inline.} =
  347. when nimvm: result = load4e(s, o)
  348. else:
  349. when declared copyMem: copyMem result.addr, s[o].addr, result.sizeof
  350. else: result = load4e(s, o)
  351. proc load8(s: openArray[byte], o=0): uint64 {.inline.} =
  352. when nimvm: result = load8e(s, o)
  353. else:
  354. when declared copyMem: copyMem result.addr, s[o].addr, result.sizeof
  355. else: result = load8e(s, o)
  356. proc lenU(s: openArray[byte]): uint64 {.inline.} = s.len.uint64
  357. proc shiftMix(v: uint64): uint64 {.inline.} = v xor (v shr 47)
  358. proc rotR(v: uint64; bits: cint): uint64 {.inline.} =
  359. (v shr bits) or (v shl (64 - bits))
  360. proc len16(u: uint64; v: uint64; mul: uint64): uint64 {.inline.} =
  361. var a = (u xor v)*mul
  362. a = a xor (a shr 47)
  363. var b = (v xor a)*mul
  364. b = b xor (b shr 47)
  365. b*mul
  366. proc len0_16(s: openArray[byte]): uint64 {.inline.} =
  367. if s.len >= 8:
  368. let mul = k2 + 2*s.lenU
  369. let a = load8(s) + k2
  370. let b = load8(s, s.len - 8)
  371. let c = rotR(b, 37)*mul + a
  372. let d = (rotR(a, 25) + b)*mul
  373. len16 c, d, mul
  374. elif s.len >= 4:
  375. let mul = k2 + 2*s.lenU
  376. let a = load4(s).uint64
  377. len16 s.lenU + (a shl 3), load4(s, s.len - 4), mul
  378. elif s.len > 0:
  379. let a = uint32(s[0])
  380. let b = uint32(s[s.len shr 1])
  381. let c = uint32(s[s.len - 1])
  382. let y = a + (b shl 8)
  383. let z = s.lenU + (c shl 2)
  384. shiftMix(y*k2 xor z*k0)*k2
  385. else: k2 # s.len == 0
  386. proc len17_32(s: openArray[byte]): uint64 {.inline.} =
  387. let mul = k2 + 2*s.lenU
  388. let a = load8(s)*k1
  389. let b = load8(s, 8)
  390. let c = load8(s, s.len - 8)*mul
  391. let d = load8(s, s.len - 16)*k2
  392. len16 rotR(a + b, 43) + rotR(c, 30) + d, a + rotR(b + k2, 18) + c, mul
  393. proc len33_64(s: openArray[byte]): uint64 {.inline.} =
  394. let mul = k2 + 2*s.lenU
  395. let a = load8(s)*k2
  396. let b = load8(s, 8)
  397. let c = load8(s, s.len - 8)*mul
  398. let d = load8(s, s.len - 16)*k2
  399. let y = rotR(a + b, 43) + rotR(c, 30) + d
  400. let z = len16(y, a + rotR(b + k2, 18) + c, mul)
  401. let e = load8(s, 16)*mul
  402. let f = load8(s, 24)
  403. let g = (y + load8(s, s.len - 32))*mul
  404. let h = (z + load8(s, s.len - 24))*mul
  405. len16 rotR(e + f, 43) + rotR(g, 30) + h, e + rotR(f + a, 18) + g, mul
  406. type Pair = tuple[first, second: uint64]
  407. proc weakLen32withSeeds2(w, x, y, z, a, b: uint64): Pair {.inline.} =
  408. var a = a + w
  409. var b = rotR(b + a + z, 21)
  410. let c = a
  411. a += x
  412. a += y
  413. b += rotR(a, 44)
  414. result[0] = a + z
  415. result[1] = b + c
  416. proc weakLen32withSeeds(s: openArray[byte]; o: int; a,b: uint64): Pair {.inline.} =
  417. weakLen32withSeeds2 load8(s, o ), load8(s, o + 8),
  418. load8(s, o + 16), load8(s, o + 24), a, b
  419. proc hashFarm(s: openArray[byte]): uint64 {.inline.} =
  420. if s.len <= 16: return len0_16(s)
  421. if s.len <= 32: return len17_32(s)
  422. if s.len <= 64: return len33_64(s)
  423. const seed = 81u64 # not const to use input `h`
  424. var
  425. o = 0 # s[] ptr arith -> variable origin variable `o`
  426. x = seed
  427. y = seed*k1 + 113
  428. z = shiftMix(y*k2 + 113)*k2
  429. v, w: Pair
  430. x = x*k2 + load8(s)
  431. let eos = ((s.len - 1) div 64)*64
  432. let last64 = eos + ((s.len - 1) and 63) - 63
  433. while true:
  434. x = rotR(x + y + v[0] + load8(s, o+8), 37)*k1
  435. y = rotR(y + v[1] + load8(s, o+48), 42)*k1
  436. x = x xor w[1]
  437. y += v[0] + load8(s, o+40)
  438. z = rotR(z + w[0], 33)*k1
  439. v = weakLen32withSeeds(s, o+0 , v[1]*k1, x + w[0])
  440. w = weakLen32withSeeds(s, o+32, z + w[1], y + load8(s, o+16))
  441. swap z, x
  442. inc o, 64
  443. if o == eos: break
  444. let mul = k1 + ((z and 0xff) shl 1)
  445. o = last64
  446. w[0] += (s.lenU - 1) and 63
  447. v[0] += w[0]
  448. w[0] += v[0]
  449. x = rotR(x + y + v[0] + load8(s, o+8), 37)*mul
  450. y = rotR(y + v[1] + load8(s, o+48), 42)*mul
  451. x = x xor w[1]*9
  452. y += v[0]*9 + load8(s, o+40)
  453. z = rotR(z + w[0], 33)*mul
  454. v = weakLen32withSeeds(s, o+0 , v[1]*mul, x + w[0])
  455. w = weakLen32withSeeds(s, o+32, z + w[1], y + load8(s, o+16))
  456. swap z, x
  457. len16 len16(v[0],w[0],mul) + shiftMix(y)*k0 + z, len16(v[1],w[1],mul) + x, mul
  458. proc hash*(x: string): Hash =
  459. ## Efficient hashing of strings.
  460. ##
  461. ## **See also:**
  462. ## * `hashIgnoreStyle <#hashIgnoreStyle,string>`_
  463. ## * `hashIgnoreCase <#hashIgnoreCase,string>`_
  464. runnableExamples:
  465. doAssert hash("abracadabra") != hash("AbracadabrA")
  466. when defined nimPreviewHashFarm: # Default switched -> `not nimStringHash2`
  467. result = cast[Hash](hashFarm(toOpenArrayByte(x, 0, x.high)))
  468. else:
  469. when nimvm:
  470. result = hashVmImpl(x, 0, high(x))
  471. else:
  472. result = murmurHash(toOpenArrayByte(x, 0, high(x)))
  473. proc hash*(x: cstring): Hash =
  474. ## Efficient hashing of null-terminated strings.
  475. runnableExamples:
  476. doAssert hash(cstring"abracadabra") == hash("abracadabra")
  477. doAssert hash(cstring"AbracadabrA") == hash("AbracadabrA")
  478. doAssert hash(cstring"abracadabra") != hash(cstring"AbracadabrA")
  479. when defined nimPreviewHashFarm: # Default switched -> `not nimStringHash2`
  480. when defined js:
  481. let xx = $x
  482. result = cast[Hash](hashFarm(toOpenArrayByte(xx, 0, xx.high)))
  483. else:
  484. result = cast[Hash](hashFarm(toOpenArrayByte(x, 0, x.high)))
  485. else:
  486. when nimvm:
  487. hashVmImpl(x, 0, high(x))
  488. else:
  489. when not defined(js):
  490. murmurHash(toOpenArrayByte(x, 0, x.high))
  491. else:
  492. let xx = $x
  493. murmurHash(toOpenArrayByte(xx, 0, high(xx)))
  494. proc hash*(sBuf: string, sPos, ePos: int): Hash =
  495. ## Efficient hashing of a string buffer, from starting
  496. ## position `sPos` to ending position `ePos` (included).
  497. ##
  498. ## `hash(myStr, 0, myStr.high)` is equivalent to `hash(myStr)`.
  499. runnableExamples:
  500. var a = "abracadabra"
  501. doAssert hash(a, 0, 3) == hash(a, 7, 10)
  502. when defined nimPreviewHashFarm: # Default switched -> `not nimStringHash2`
  503. result = cast[Hash](hashFarm(toOpenArrayByte(sBuf, sPos, ePos)))
  504. else:
  505. murmurHash(toOpenArrayByte(sBuf, sPos, ePos))
  506. proc hashIgnoreStyle*(x: string): Hash =
  507. ## Efficient hashing of strings; style is ignored.
  508. ##
  509. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  510. ##
  511. ## **See also:**
  512. ## * `hashIgnoreCase <#hashIgnoreCase,string>`_
  513. runnableExamples:
  514. doAssert hashIgnoreStyle("aBr_aCa_dAB_ra") == hashIgnoreStyle("abracadabra")
  515. doAssert hashIgnoreStyle("abcdefghi") != hash("abcdefghi")
  516. var h: Hash = 0
  517. var i = 0
  518. let xLen = x.len
  519. while i < xLen:
  520. var c = x[i]
  521. if c == '_':
  522. inc(i)
  523. else:
  524. if c in {'A'..'Z'}:
  525. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  526. h = h !& ord(c)
  527. inc(i)
  528. result = !$h
  529. proc hashIgnoreStyle*(sBuf: string, sPos, ePos: int): Hash =
  530. ## Efficient hashing of a string buffer, from starting
  531. ## position `sPos` to ending position `ePos` (included); style is ignored.
  532. ##
  533. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  534. ##
  535. ## `hashIgnoreStyle(myBuf, 0, myBuf.high)` is equivalent
  536. ## to `hashIgnoreStyle(myBuf)`.
  537. runnableExamples:
  538. var a = "ABracada_b_r_a"
  539. doAssert hashIgnoreStyle(a, 0, 3) == hashIgnoreStyle(a, 7, a.high)
  540. var h: Hash = 0
  541. var i = sPos
  542. while i <= ePos:
  543. var c = sBuf[i]
  544. if c == '_':
  545. inc(i)
  546. else:
  547. if c in {'A'..'Z'}:
  548. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  549. h = h !& ord(c)
  550. inc(i)
  551. result = !$h
  552. proc hashIgnoreCase*(x: string): Hash =
  553. ## Efficient hashing of strings; case is ignored.
  554. ##
  555. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  556. ##
  557. ## **See also:**
  558. ## * `hashIgnoreStyle <#hashIgnoreStyle,string>`_
  559. runnableExamples:
  560. doAssert hashIgnoreCase("ABRAcaDABRA") == hashIgnoreCase("abRACAdabra")
  561. doAssert hashIgnoreCase("abcdefghi") != hash("abcdefghi")
  562. var h: Hash = 0
  563. for i in 0..x.len-1:
  564. var c = x[i]
  565. if c in {'A'..'Z'}:
  566. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  567. h = h !& ord(c)
  568. result = !$h
  569. proc hashIgnoreCase*(sBuf: string, sPos, ePos: int): Hash =
  570. ## Efficient hashing of a string buffer, from starting
  571. ## position `sPos` to ending position `ePos` (included); case is ignored.
  572. ##
  573. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  574. ##
  575. ## `hashIgnoreCase(myBuf, 0, myBuf.high)` is equivalent
  576. ## to `hashIgnoreCase(myBuf)`.
  577. runnableExamples:
  578. var a = "ABracadabRA"
  579. doAssert hashIgnoreCase(a, 0, 3) == hashIgnoreCase(a, 7, 10)
  580. var h: Hash = 0
  581. for i in sPos..ePos:
  582. var c = sBuf[i]
  583. if c in {'A'..'Z'}:
  584. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  585. h = h !& ord(c)
  586. result = !$h
  587. proc hash*[T: tuple | object | proc | iterator {.closure.}](x: T): Hash =
  588. ## Efficient `hash` overload.
  589. runnableExamples:
  590. # for `tuple|object`, `hash` must be defined for each component of `x`.
  591. type Obj = object
  592. x: int
  593. y: string
  594. type Obj2[T] = object
  595. x: int
  596. y: string
  597. assert hash(Obj(x: 520, y: "Nim")) != hash(Obj(x: 520, y: "Nim2"))
  598. # you can define custom hashes for objects (even if they're generic):
  599. proc hash(a: Obj2): Hash = hash((a.x))
  600. assert hash(Obj2[float](x: 520, y: "Nim")) == hash(Obj2[float](x: 520, y: "Nim2"))
  601. runnableExamples:
  602. # proc
  603. proc fn1() = discard
  604. const fn1b = fn1
  605. assert hash(fn1b) == hash(fn1)
  606. # closure
  607. proc outer =
  608. var a = 0
  609. proc fn2() = a.inc
  610. assert fn2 is "closure"
  611. let fn2b = fn2
  612. assert hash(fn2b) == hash(fn2)
  613. assert hash(fn2) != hash(fn1)
  614. outer()
  615. when T is "closure":
  616. result = hash((rawProc(x), rawEnv(x)))
  617. elif T is (proc):
  618. result = hash(cast[pointer](x))
  619. else:
  620. result = 0
  621. for f in fields(x):
  622. result = result !& hash(f)
  623. result = !$result
  624. proc hash*[A](x: openArray[A]): Hash =
  625. ## Efficient hashing of arrays and sequences.
  626. ## There must be a `hash` proc defined for the element type `A`.
  627. when A is byte:
  628. when defined nimPreviewHashFarm: # Default switched -> `not nimStringHash2`
  629. result = cast[Hash](hashFarm(x))
  630. else:
  631. result = murmurHash(x)
  632. elif A is char:
  633. when defined nimPreviewHashFarm: # Default switched -> `not nimStringHash2`
  634. result = cast[Hash](hashFarm(toOpenArrayByte(x, 0, x.high)))
  635. else:
  636. when nimvm:
  637. result = hashVmImplChar(x, 0, x.high)
  638. else:
  639. result = murmurHash(toOpenArrayByte(x, 0, x.high))
  640. else:
  641. result = 0
  642. for a in x:
  643. result = result !& hash(a)
  644. result = !$result
  645. proc hash*[A](aBuf: openArray[A], sPos, ePos: int): Hash =
  646. ## Efficient hashing of portions of arrays and sequences, from starting
  647. ## position `sPos` to ending position `ePos` (included).
  648. ## There must be a `hash` proc defined for the element type `A`.
  649. ##
  650. ## `hash(myBuf, 0, myBuf.high)` is equivalent to `hash(myBuf)`.
  651. runnableExamples:
  652. let a = [1, 2, 5, 1, 2, 6]
  653. doAssert hash(a, 0, 1) == hash(a, 3, 4)
  654. when A is byte:
  655. when defined nimPreviewHashFarm: # Default switched -> `not nimStringHash2`
  656. result = cast[Hash](hashFarm(toOpenArray(aBuf, sPos, ePos)))
  657. else:
  658. when nimvm:
  659. result = hashVmImplByte(aBuf, sPos, ePos)
  660. else:
  661. result = murmurHash(toOpenArray(aBuf, sPos, ePos))
  662. elif A is char:
  663. when defined nimPreviewHashFarm: # Default switched -> `not nimStringHash2`
  664. result = cast[Hash](hashFarm(toOpenArrayByte(aBuf, sPos, ePos)))
  665. else:
  666. when nimvm:
  667. result = hashVmImplChar(aBuf, sPos, ePos)
  668. else:
  669. result = murmurHash(toOpenArrayByte(aBuf, sPos, ePos))
  670. else:
  671. for i in sPos .. ePos:
  672. result = result !& hash(aBuf[i])
  673. result = !$result
  674. proc hash*[A](x: set[A]): Hash =
  675. ## Efficient hashing of sets.
  676. ## There must be a `hash` proc defined for the element type `A`.
  677. result = 0
  678. for it in items(x):
  679. result = result !& hash(it)
  680. result = !$result