hashes.nim 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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, jsutils]
  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. result = uint64(0)
  110. {.emit: """__uint128_t r = `a`; r *= `b`; `result` = (r >> 64) ^ r;""".}
  111. elif defined(windows) and not defined(tcc):
  112. proc umul128(a, b: uint64, c: ptr uint64): uint64 {.importc: "_umul128", header: "intrin.h".}
  113. var b = b
  114. let c = umul128(a, b, addr b)
  115. result = c xor b
  116. else:
  117. result = hiXorLoFallback64(a, b)
  118. when defined(js):
  119. import std/jsbigints
  120. import std/private/jsutils
  121. proc hiXorLoJs(a, b: JsBigInt): JsBigInt =
  122. let
  123. prod = a * b
  124. mask = big"0xffffffffffffffff" # (big"1" shl big"64") - big"1"
  125. result = (prod shr big"64") xor (prod and mask)
  126. template hashWangYiJS(x: JsBigInt): Hash =
  127. let
  128. P0 = big"0xa0761d6478bd642f"
  129. P1 = big"0xe7037ed1a0b428db"
  130. P58 = big"0xeb44accab455d16d" # big"0xeb44accab455d165" xor big"8"
  131. res = hiXorLoJs(hiXorLoJs(P0, x xor P1), P58)
  132. cast[Hash](toNumber(wrapToInt(res, 32)))
  133. template toBits(num: float): JsBigInt =
  134. let
  135. x = newArrayBuffer(8)
  136. y = newFloat64Array(x)
  137. if hasBigUint64Array():
  138. let z = newBigUint64Array(x)
  139. y[0] = num
  140. z[0]
  141. else:
  142. let z = newUint32Array(x)
  143. y[0] = num
  144. big(z[0]) + big(z[1]) shl big(32)
  145. proc hashWangYi1*(x: int64|uint64|Hash): Hash {.inline.} =
  146. ## Wang Yi's hash_v1 for 64-bit ints (see https://github.com/rurban/smhasher for
  147. ## more details). This passed all scrambling tests in Spring 2019 and is simple.
  148. ##
  149. ## **Note:** It's ok to define `proc(x: int16): Hash = hashWangYi1(Hash(x))`.
  150. const P0 = 0xa0761d6478bd642f'u64
  151. const P1 = 0xe7037ed1a0b428db'u64
  152. const P58 = 0xeb44accab455d165'u64 xor 8'u64
  153. template h(x): untyped = hiXorLo(hiXorLo(P0, uint64(x) xor P1), P58)
  154. when nimvm:
  155. when defined(js): # Nim int64<->JS Number & VM match => JS gets 32-bit hash
  156. result = cast[Hash](h(x)) and cast[Hash](0xFFFFFFFF)
  157. else:
  158. result = cast[Hash](h(x))
  159. else:
  160. when defined(js):
  161. if hasJsBigInt():
  162. result = hashWangYiJS(big(x))
  163. else:
  164. result = cast[Hash](x) and cast[Hash](0xFFFFFFFF)
  165. else:
  166. result = cast[Hash](h(x))
  167. proc hashData*(data: pointer, size: int): Hash =
  168. ## Hashes an array of bytes of size `size`.
  169. var h: Hash = 0
  170. when defined(js):
  171. var p: cstring
  172. {.emit: """`p` = `Data`;""".}
  173. else:
  174. var p = cast[cstring](data)
  175. var i = 0
  176. var s = size
  177. while s > 0:
  178. h = h !& ord(p[i])
  179. inc(i)
  180. dec(s)
  181. result = !$h
  182. proc hashIdentity*[T: Ordinal|enum](x: T): Hash {.inline, since: (1, 3).} =
  183. ## The identity hash, i.e. `hashIdentity(x) = x`.
  184. cast[Hash](ord(x))
  185. when defined(nimIntHash1):
  186. proc hash*[T: Ordinal|enum](x: T): Hash {.inline.} =
  187. ## Efficient hashing of integers.
  188. cast[Hash](ord(x))
  189. else:
  190. proc hash*[T: Ordinal|enum](x: T): Hash {.inline.} =
  191. ## Efficient hashing of integers.
  192. hashWangYi1(uint64(ord(x)))
  193. when defined(js):
  194. var objectID = 0
  195. proc getObjectId(x: pointer): int =
  196. {.emit: """
  197. if (typeof `x` == "object") {
  198. if ("_NimID" in `x`)
  199. `result` = `x`["_NimID"];
  200. else {
  201. `result` = ++`objectID`;
  202. `x`["_NimID"] = `result`;
  203. }
  204. }
  205. """.}
  206. proc hash*(x: pointer): Hash {.inline.} =
  207. ## Efficient `hash` overload.
  208. when defined(js):
  209. let y = getObjectId(x)
  210. else:
  211. let y = cast[int](x)
  212. hash(y) # consistent with code expecting scrambled hashes depending on `nimIntHash1`.
  213. proc hash*[T](x: ptr[T]): Hash {.inline.} =
  214. ## Efficient `hash` overload.
  215. runnableExamples:
  216. var a: array[10, uint8]
  217. assert a[0].addr.hash != a[1].addr.hash
  218. assert cast[pointer](a[0].addr).hash == a[0].addr.hash
  219. hash(cast[pointer](x))
  220. when defined(nimPreviewHashRef) or defined(nimdoc):
  221. proc hash*[T](x: ref[T]): Hash {.inline.} =
  222. ## Efficient `hash` overload.
  223. ##
  224. ## .. important:: Use `-d:nimPreviewHashRef` to
  225. ## enable hashing `ref`s. It is expected that this behavior
  226. ## becomes the new default in upcoming versions.
  227. runnableExamples("-d:nimPreviewHashRef"):
  228. type A = ref object
  229. x: int
  230. let a = A(x: 3)
  231. let ha = a.hash
  232. assert ha != A(x: 3).hash # A(x: 3) is a different ref object from `a`.
  233. a.x = 4
  234. assert ha == a.hash # the hash only depends on the address
  235. runnableExamples("-d:nimPreviewHashRef"):
  236. # you can overload `hash` if you want to customize semantics
  237. type A[T] = ref object
  238. x, y: T
  239. proc hash(a: A): Hash = hash(a.x)
  240. assert A[int](x: 3, y: 4).hash == A[int](x: 3, y: 5).hash
  241. # xxx pending bug #17733, merge as `proc hash*(pointer | ref | ptr): Hash`
  242. # or `proc hash*[T: ref | ptr](x: T): Hash`
  243. hash(cast[pointer](x))
  244. proc hash*(x: float): Hash {.inline.} =
  245. ## Efficient hashing of floats.
  246. let y = x + 0.0 # for denormalization
  247. when nimvm:
  248. # workaround a JS VM bug: bug #16547
  249. result = hashWangYi1(cast[int64](float64(y)))
  250. else:
  251. when not defined(js):
  252. result = hashWangYi1(cast[Hash](y))
  253. else:
  254. result = hashWangYiJS(toBits(y))
  255. # Forward declarations before methods that hash containers. This allows
  256. # containers to contain other containers
  257. proc hash*[A](x: openArray[A]): Hash
  258. proc hash*[A](x: set[A]): Hash
  259. when defined(js):
  260. proc imul(a, b: uint32): uint32 =
  261. # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
  262. let mask = 0xffff'u32
  263. var
  264. aHi = (a shr 16) and mask
  265. aLo = a and mask
  266. bHi = (b shr 16) and mask
  267. bLo = b and mask
  268. result = (aLo * bLo) + (aHi * bLo + aLo * bHi) shl 16
  269. else:
  270. template imul(a, b: uint32): untyped = a * b
  271. proc rotl32(x: uint32, r: int): uint32 {.inline.} =
  272. (x shl r) or (x shr (32 - r))
  273. proc murmurHash(x: openArray[byte]): Hash =
  274. # https://github.com/PeterScott/murmur3/blob/master/murmur3.c
  275. const
  276. c1 = 0xcc9e2d51'u32
  277. c2 = 0x1b873593'u32
  278. n1 = 0xe6546b64'u32
  279. m1 = 0x85ebca6b'u32
  280. m2 = 0xc2b2ae35'u32
  281. let
  282. size = len(x)
  283. stepSize = 4 # 32-bit
  284. n = size div stepSize
  285. var
  286. h1: uint32 = uint32(0)
  287. i = 0
  288. template impl =
  289. var j = stepSize
  290. while j > 0:
  291. dec j
  292. k1 = (k1 shl 8) or (ord(x[i+j])).uint32
  293. # body
  294. while i < n * stepSize:
  295. var k1: uint32 = uint32(0)
  296. when nimvm:
  297. impl()
  298. else:
  299. when declared(copyMem):
  300. copyMem(addr k1, addr x[i], 4)
  301. else:
  302. impl()
  303. inc i, stepSize
  304. k1 = imul(k1, c1)
  305. k1 = rotl32(k1, 15)
  306. k1 = imul(k1, c2)
  307. h1 = h1 xor k1
  308. h1 = rotl32(h1, 13)
  309. h1 = h1*5 + n1
  310. # tail
  311. var k1: uint32 = uint32(0)
  312. var rem = size mod stepSize
  313. while rem > 0:
  314. dec rem
  315. k1 = (k1 shl 8) or (ord(x[i+rem])).uint32
  316. k1 = imul(k1, c1)
  317. k1 = rotl32(k1, 15)
  318. k1 = imul(k1, c2)
  319. h1 = h1 xor k1
  320. # finalization
  321. h1 = h1 xor size.uint32
  322. h1 = h1 xor (h1 shr 16)
  323. h1 = imul(h1, m1)
  324. h1 = h1 xor (h1 shr 13)
  325. h1 = imul(h1, m2)
  326. h1 = h1 xor (h1 shr 16)
  327. return cast[Hash](h1)
  328. proc hashVmImpl(x: cstring, sPos, ePos: int): Hash =
  329. raiseAssert "implementation override in compiler/vmops.nim"
  330. proc hashVmImpl(x: string, sPos, ePos: int): Hash =
  331. raiseAssert "implementation override in compiler/vmops.nim"
  332. proc hashVmImplChar(x: openArray[char], sPos, ePos: int): Hash =
  333. raiseAssert "implementation override in compiler/vmops.nim"
  334. proc hashVmImplByte(x: openArray[byte], sPos, ePos: int): Hash =
  335. raiseAssert "implementation override in compiler/vmops.nim"
  336. const k0 = 0xc3a5c85c97cb3127u64 # Primes on (2^63, 2^64) for various uses
  337. const k1 = 0xb492b66fbe98f273u64
  338. const k2 = 0x9ae16a3b2f90404fu64
  339. proc load4e(s: openArray[byte], o=0): uint32 {.inline.} =
  340. uint32(s[o + 3]) shl 24 or uint32(s[o + 2]) shl 16 or
  341. uint32(s[o + 1]) shl 8 or uint32(s[o + 0])
  342. proc load8e(s: openArray[byte], o=0): uint64 {.inline.} =
  343. uint64(s[o + 7]) shl 56 or uint64(s[o + 6]) shl 48 or
  344. uint64(s[o + 5]) shl 40 or uint64(s[o + 4]) shl 32 or
  345. uint64(s[o + 3]) shl 24 or uint64(s[o + 2]) shl 16 or
  346. uint64(s[o + 1]) shl 8 or uint64(s[o + 0])
  347. proc load4(s: openArray[byte], o=0): uint32 {.inline.} =
  348. when nimvm: result = load4e(s, o)
  349. else:
  350. when declared copyMem:
  351. result = uint32(0)
  352. copyMem result.addr, s[o].addr, result.sizeof
  353. else: result = load4e(s, o)
  354. proc load8(s: openArray[byte], o=0): uint64 {.inline.} =
  355. when nimvm: result = load8e(s, o)
  356. else:
  357. when declared copyMem:
  358. result = uint64(0)
  359. copyMem result.addr, s[o].addr, result.sizeof
  360. else: result = load8e(s, o)
  361. proc lenU(s: openArray[byte]): uint64 {.inline.} = s.len.uint64
  362. proc shiftMix(v: uint64): uint64 {.inline.} = v xor (v shr 47)
  363. proc rotR(v: uint64; bits: cint): uint64 {.inline.} =
  364. (v shr bits) or (v shl (64 - bits))
  365. proc len16(u: uint64; v: uint64; mul: uint64): uint64 {.inline.} =
  366. var a = (u xor v)*mul
  367. a = a xor (a shr 47)
  368. var b = (v xor a)*mul
  369. b = b xor (b shr 47)
  370. b*mul
  371. proc len0_16(s: openArray[byte]): uint64 {.inline.} =
  372. if s.len >= 8:
  373. let mul = k2 + 2*s.lenU
  374. let a = load8(s) + k2
  375. let b = load8(s, s.len - 8)
  376. let c = rotR(b, 37)*mul + a
  377. let d = (rotR(a, 25) + b)*mul
  378. len16 c, d, mul
  379. elif s.len >= 4:
  380. let mul = k2 + 2*s.lenU
  381. let a = load4(s).uint64
  382. len16 s.lenU + (a shl 3), load4(s, s.len - 4), mul
  383. elif s.len > 0:
  384. let a = uint32(s[0])
  385. let b = uint32(s[s.len shr 1])
  386. let c = uint32(s[s.len - 1])
  387. let y = a + (b shl 8)
  388. let z = s.lenU + (c shl 2)
  389. shiftMix(y*k2 xor z*k0)*k2
  390. else: k2 # s.len == 0
  391. proc len17_32(s: openArray[byte]): uint64 {.inline.} =
  392. let mul = k2 + 2*s.lenU
  393. let a = load8(s)*k1
  394. let b = load8(s, 8)
  395. let c = load8(s, s.len - 8)*mul
  396. let d = load8(s, s.len - 16)*k2
  397. len16 rotR(a + b, 43) + rotR(c, 30) + d, a + rotR(b + k2, 18) + c, mul
  398. proc len33_64(s: openArray[byte]): uint64 {.inline.} =
  399. let mul = k2 + 2*s.lenU
  400. let a = load8(s)*k2
  401. let b = load8(s, 8)
  402. let c = load8(s, s.len - 8)*mul
  403. let d = load8(s, s.len - 16)*k2
  404. let y = rotR(a + b, 43) + rotR(c, 30) + d
  405. let z = len16(y, a + rotR(b + k2, 18) + c, mul)
  406. let e = load8(s, 16)*mul
  407. let f = load8(s, 24)
  408. let g = (y + load8(s, s.len - 32))*mul
  409. let h = (z + load8(s, s.len - 24))*mul
  410. len16 rotR(e + f, 43) + rotR(g, 30) + h, e + rotR(f + a, 18) + g, mul
  411. type Pair = tuple[first, second: uint64]
  412. proc weakLen32withSeeds2(w, x, y, z, a, b: uint64): Pair {.inline.} =
  413. var a = a + w
  414. var b = rotR(b + a + z, 21)
  415. let c = a
  416. a += x
  417. a += y
  418. b += rotR(a, 44)
  419. result[0] = a + z
  420. result[1] = b + c
  421. proc weakLen32withSeeds(s: openArray[byte]; o: int; a,b: uint64): Pair {.inline.} =
  422. weakLen32withSeeds2 load8(s, o ), load8(s, o + 8),
  423. load8(s, o + 16), load8(s, o + 24), a, b
  424. proc hashFarm(s: openArray[byte]): uint64 {.inline.} =
  425. if s.len <= 16: return len0_16(s)
  426. if s.len <= 32: return len17_32(s)
  427. if s.len <= 64: return len33_64(s)
  428. const seed = 81u64 # not const to use input `h`
  429. var
  430. o = 0 # s[] ptr arith -> variable origin variable `o`
  431. x = seed
  432. y = seed*k1 + 113
  433. z = shiftMix(y*k2 + 113)*k2
  434. v, w: Pair = default(Pair)
  435. x = x*k2 + load8(s)
  436. let eos = ((s.len - 1) div 64)*64
  437. let last64 = eos + ((s.len - 1) and 63) - 63
  438. while true:
  439. x = rotR(x + y + v[0] + load8(s, o+8), 37)*k1
  440. y = rotR(y + v[1] + load8(s, o+48), 42)*k1
  441. x = x xor w[1]
  442. y += v[0] + load8(s, o+40)
  443. z = rotR(z + w[0], 33)*k1
  444. v = weakLen32withSeeds(s, o+0 , v[1]*k1, x + w[0])
  445. w = weakLen32withSeeds(s, o+32, z + w[1], y + load8(s, o+16))
  446. swap z, x
  447. inc o, 64
  448. if o == eos: break
  449. let mul = k1 + ((z and 0xff) shl 1)
  450. o = last64
  451. w[0] += (s.lenU - 1) and 63
  452. v[0] += w[0]
  453. w[0] += v[0]
  454. x = rotR(x + y + v[0] + load8(s, o+8), 37)*mul
  455. y = rotR(y + v[1] + load8(s, o+48), 42)*mul
  456. x = x xor w[1]*9
  457. y += v[0]*9 + load8(s, o+40)
  458. z = rotR(z + w[0], 33)*mul
  459. v = weakLen32withSeeds(s, o+0 , v[1]*mul, x + w[0])
  460. w = weakLen32withSeeds(s, o+32, z + w[1], y + load8(s, o+16))
  461. swap z, x
  462. len16 len16(v[0],w[0],mul) + shiftMix(y)*k0 + z, len16(v[1],w[1],mul) + x, mul
  463. const sHash2 = defined(nimStringHash2) or jsNoBigInt64
  464. template maybeFailJS_Number =
  465. when jsNoBigInt64 and not defined(nimStringHash2):
  466. {.error: "Must use `-d:nimStringHash2` when using `--jsbigint64:off`".}
  467. proc hash*(x: string): Hash =
  468. ## Efficient hashing of strings.
  469. ##
  470. ## **See also:**
  471. ## * `hashIgnoreStyle <#hashIgnoreStyle,string>`_
  472. ## * `hashIgnoreCase <#hashIgnoreCase,string>`_
  473. runnableExamples:
  474. doAssert hash("abracadabra") != hash("AbracadabrA")
  475. maybeFailJS_Number()
  476. when not sHash2:
  477. result = cast[Hash](hashFarm(toOpenArrayByte(x, 0, x.high)))
  478. else:
  479. #when nimvm:
  480. # result = hashVmImpl(x, 0, high(x))
  481. when true:
  482. result = murmurHash(toOpenArrayByte(x, 0, high(x)))
  483. proc hash*(x: cstring): Hash =
  484. ## Efficient hashing of null-terminated strings.
  485. runnableExamples:
  486. doAssert hash(cstring"abracadabra") == hash("abracadabra")
  487. doAssert hash(cstring"AbracadabrA") == hash("AbracadabrA")
  488. doAssert hash(cstring"abracadabra") != hash(cstring"AbracadabrA")
  489. maybeFailJS_Number()
  490. when not sHash2:
  491. when defined js:
  492. let xx = $x
  493. result = cast[Hash](hashFarm(toOpenArrayByte(xx, 0, xx.high)))
  494. else:
  495. result = cast[Hash](hashFarm(toOpenArrayByte(x, 0, x.high)))
  496. else:
  497. #when nimvm:
  498. # result = hashVmImpl(x, 0, high(x))
  499. when true:
  500. when not defined(js):
  501. result = murmurHash(toOpenArrayByte(x, 0, x.high))
  502. else:
  503. let xx = $x
  504. result = murmurHash(toOpenArrayByte(xx, 0, high(xx)))
  505. proc hash*(sBuf: string, sPos, ePos: int): Hash =
  506. ## Efficient hashing of a string buffer, from starting
  507. ## position `sPos` to ending position `ePos` (included).
  508. ##
  509. ## `hash(myStr, 0, myStr.high)` is equivalent to `hash(myStr)`.
  510. runnableExamples:
  511. var a = "abracadabra"
  512. doAssert hash(a, 0, 3) == hash(a, 7, 10)
  513. maybeFailJS_Number()
  514. when not sHash2:
  515. result = cast[Hash](hashFarm(toOpenArrayByte(sBuf, sPos, ePos)))
  516. else:
  517. murmurHash(toOpenArrayByte(sBuf, sPos, ePos))
  518. proc hashIgnoreStyle*(x: string): Hash =
  519. ## Efficient hashing of strings; style is ignored.
  520. ##
  521. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  522. ##
  523. ## **See also:**
  524. ## * `hashIgnoreCase <#hashIgnoreCase,string>`_
  525. runnableExamples:
  526. doAssert hashIgnoreStyle("aBr_aCa_dAB_ra") == hashIgnoreStyle("abracadabra")
  527. doAssert hashIgnoreStyle("abcdefghi") != hash("abcdefghi")
  528. var h: Hash = 0
  529. var i = 0
  530. let xLen = x.len
  531. while i < xLen:
  532. var c = x[i]
  533. if c == '_':
  534. inc(i)
  535. else:
  536. if c in {'A'..'Z'}:
  537. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  538. h = h !& ord(c)
  539. inc(i)
  540. result = !$h
  541. proc hashIgnoreStyle*(sBuf: string, sPos, ePos: int): Hash =
  542. ## Efficient hashing of a string buffer, from starting
  543. ## position `sPos` to ending position `ePos` (included); style is ignored.
  544. ##
  545. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  546. ##
  547. ## `hashIgnoreStyle(myBuf, 0, myBuf.high)` is equivalent
  548. ## to `hashIgnoreStyle(myBuf)`.
  549. runnableExamples:
  550. var a = "ABracada_b_r_a"
  551. doAssert hashIgnoreStyle(a, 0, 3) == hashIgnoreStyle(a, 7, a.high)
  552. var h: Hash = 0
  553. var i = sPos
  554. while i <= ePos:
  555. var c = sBuf[i]
  556. if c == '_':
  557. inc(i)
  558. else:
  559. if c in {'A'..'Z'}:
  560. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  561. h = h !& ord(c)
  562. inc(i)
  563. result = !$h
  564. proc hashIgnoreCase*(x: string): Hash =
  565. ## Efficient hashing of strings; case is ignored.
  566. ##
  567. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  568. ##
  569. ## **See also:**
  570. ## * `hashIgnoreStyle <#hashIgnoreStyle,string>`_
  571. runnableExamples:
  572. doAssert hashIgnoreCase("ABRAcaDABRA") == hashIgnoreCase("abRACAdabra")
  573. doAssert hashIgnoreCase("abcdefghi") != hash("abcdefghi")
  574. var h: Hash = 0
  575. for i in 0..x.len-1:
  576. var c = x[i]
  577. if c in {'A'..'Z'}:
  578. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  579. h = h !& ord(c)
  580. result = !$h
  581. proc hashIgnoreCase*(sBuf: string, sPos, ePos: int): Hash =
  582. ## Efficient hashing of a string buffer, from starting
  583. ## position `sPos` to ending position `ePos` (included); case is ignored.
  584. ##
  585. ## **Note:** This uses a different hashing algorithm than `hash(string)`.
  586. ##
  587. ## `hashIgnoreCase(myBuf, 0, myBuf.high)` is equivalent
  588. ## to `hashIgnoreCase(myBuf)`.
  589. runnableExamples:
  590. var a = "ABracadabRA"
  591. doAssert hashIgnoreCase(a, 0, 3) == hashIgnoreCase(a, 7, 10)
  592. var h: Hash = 0
  593. for i in sPos..ePos:
  594. var c = sBuf[i]
  595. if c in {'A'..'Z'}:
  596. c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
  597. h = h !& ord(c)
  598. result = !$h
  599. proc hash*[T: tuple | object | proc | iterator {.closure.}](x: T): Hash =
  600. ## Efficient `hash` overload.
  601. runnableExamples:
  602. # for `tuple|object`, `hash` must be defined for each component of `x`.
  603. type Obj = object
  604. x: int
  605. y: string
  606. type Obj2[T] = object
  607. x: int
  608. y: string
  609. assert hash(Obj(x: 520, y: "Nim")) != hash(Obj(x: 520, y: "Nim2"))
  610. # you can define custom hashes for objects (even if they're generic):
  611. proc hash(a: Obj2): Hash = hash((a.x))
  612. assert hash(Obj2[float](x: 520, y: "Nim")) == hash(Obj2[float](x: 520, y: "Nim2"))
  613. runnableExamples:
  614. # proc
  615. proc fn1() = discard
  616. const fn1b = fn1
  617. assert hash(fn1b) == hash(fn1)
  618. # closure
  619. proc outer =
  620. var a = 0
  621. proc fn2() = a.inc
  622. assert fn2 is "closure"
  623. let fn2b = fn2
  624. assert hash(fn2b) == hash(fn2)
  625. assert hash(fn2) != hash(fn1)
  626. outer()
  627. when T is "closure":
  628. result = hash((rawProc(x), rawEnv(x)))
  629. elif T is (proc):
  630. result = hash(cast[pointer](x))
  631. else:
  632. result = 0
  633. for f in fields(x):
  634. result = result !& hash(f)
  635. result = !$result
  636. proc hash*[A](x: openArray[A]): Hash =
  637. ## Efficient hashing of arrays and sequences.
  638. ## There must be a `hash` proc defined for the element type `A`.
  639. when A is byte:
  640. when not sHash2:
  641. result = cast[Hash](hashFarm(x))
  642. else:
  643. result = murmurHash(x)
  644. elif A is char:
  645. when not sHash2:
  646. result = cast[Hash](hashFarm(toOpenArrayByte(x, 0, x.high)))
  647. else:
  648. #when nimvm:
  649. # result = hashVmImplChar(x, 0, x.high)
  650. when true:
  651. result = murmurHash(toOpenArrayByte(x, 0, x.high))
  652. else:
  653. result = 0
  654. for a in x:
  655. result = result !& hash(a)
  656. result = !$result
  657. proc hash*[A](aBuf: openArray[A], sPos, ePos: int): Hash =
  658. ## Efficient hashing of portions of arrays and sequences, from starting
  659. ## position `sPos` to ending position `ePos` (included).
  660. ## There must be a `hash` proc defined for the element type `A`.
  661. ##
  662. ## `hash(myBuf, 0, myBuf.high)` is equivalent to `hash(myBuf)`.
  663. runnableExamples:
  664. let a = [1, 2, 5, 1, 2, 6]
  665. doAssert hash(a, 0, 1) == hash(a, 3, 4)
  666. when A is byte:
  667. maybeFailJS_Number()
  668. when not sHash2:
  669. result = cast[Hash](hashFarm(toOpenArray(aBuf, sPos, ePos)))
  670. else:
  671. #when nimvm:
  672. # result = hashVmImplByte(aBuf, sPos, ePos)
  673. when true:
  674. result = murmurHash(toOpenArray(aBuf, sPos, ePos))
  675. elif A is char:
  676. maybeFailJS_Number()
  677. when not sHash2:
  678. result = cast[Hash](hashFarm(toOpenArrayByte(aBuf, sPos, ePos)))
  679. else:
  680. #when nimvm:
  681. # result = hashVmImplChar(aBuf, sPos, ePos)
  682. when true:
  683. result = murmurHash(toOpenArrayByte(aBuf, sPos, ePos))
  684. else:
  685. for i in sPos .. ePos:
  686. result = result !& hash(aBuf[i])
  687. result = !$result
  688. proc hash*[A](x: set[A]): Hash =
  689. ## Efficient hashing of sets.
  690. ## There must be a `hash` proc defined for the element type `A`.
  691. result = 0
  692. for it in items(x):
  693. result = result !& hash(it)
  694. result = !$result