hashing.pyx 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. # Translated from the reference implementation
  2. # at https://github.com/veorq/SipHash
  3. cimport cython
  4. from libc.stdlib cimport (
  5. free,
  6. malloc,
  7. )
  8. import numpy as np
  9. from numpy cimport (
  10. import_array,
  11. ndarray,
  12. uint8_t,
  13. uint64_t,
  14. )
  15. import_array()
  16. from pandas._libs.util cimport is_nan
  17. @cython.boundscheck(False)
  18. def hash_object_array(
  19. ndarray[object] arr, str key, str encoding="utf8"
  20. ) -> np.ndarray[np.uint64]:
  21. """
  22. Parameters
  23. ----------
  24. arr : 1-d object ndarray of objects
  25. key : hash key, must be 16 byte len encoded
  26. encoding : encoding for key & arr, default to 'utf8'
  27. Returns
  28. -------
  29. 1-d uint64 ndarray of hashes.
  30. Raises
  31. ------
  32. TypeError
  33. If the array contains mixed types.
  34. Notes
  35. -----
  36. Allowed values must be strings, or nulls
  37. mixed array types will raise TypeError.
  38. """
  39. cdef:
  40. Py_ssize_t i, n
  41. uint64_t[::1] result
  42. bytes data, k
  43. uint8_t *kb
  44. uint64_t *lens
  45. char **vecs
  46. char *cdata
  47. object val
  48. list datas = []
  49. k = <bytes>key.encode(encoding)
  50. kb = <uint8_t *>k
  51. if len(k) != 16:
  52. raise ValueError(
  53. f"key should be a 16-byte string encoded, got {k} (len {len(k)})"
  54. )
  55. n = len(arr)
  56. # create an array of bytes
  57. vecs = <char **>malloc(n * sizeof(char *))
  58. lens = <uint64_t*>malloc(n * sizeof(uint64_t))
  59. for i in range(n):
  60. val = arr[i]
  61. if isinstance(val, bytes):
  62. data = <bytes>val
  63. elif isinstance(val, str):
  64. data = <bytes>val.encode(encoding)
  65. elif val is None or is_nan(val):
  66. # null, stringify and encode
  67. data = <bytes>str(val).encode(encoding)
  68. elif isinstance(val, tuple):
  69. # GH#28969 we could have a tuple, but need to ensure that
  70. # the tuple entries are themselves hashable before converting
  71. # to str
  72. hash(val)
  73. data = <bytes>str(val).encode(encoding)
  74. else:
  75. raise TypeError(
  76. f"{val} of type {type(val)} is not a valid type for hashing, "
  77. "must be string or null"
  78. )
  79. lens[i] = len(data)
  80. cdata = data
  81. # keep the references alive through the end of the
  82. # function
  83. datas.append(data)
  84. vecs[i] = cdata
  85. result = np.empty(n, dtype=np.uint64)
  86. with nogil:
  87. for i in range(n):
  88. result[i] = low_level_siphash(<uint8_t *>vecs[i], lens[i], kb)
  89. free(vecs)
  90. free(lens)
  91. return result.base # .base to retrieve underlying np.ndarray
  92. cdef uint64_t _rotl(uint64_t x, uint64_t b) nogil:
  93. return (x << b) | (x >> (64 - b))
  94. cdef uint64_t u8to64_le(uint8_t* p) nogil:
  95. return (<uint64_t>p[0] |
  96. <uint64_t>p[1] << 8 |
  97. <uint64_t>p[2] << 16 |
  98. <uint64_t>p[3] << 24 |
  99. <uint64_t>p[4] << 32 |
  100. <uint64_t>p[5] << 40 |
  101. <uint64_t>p[6] << 48 |
  102. <uint64_t>p[7] << 56)
  103. cdef void _sipround(uint64_t* v0, uint64_t* v1,
  104. uint64_t* v2, uint64_t* v3) nogil:
  105. v0[0] += v1[0]
  106. v1[0] = _rotl(v1[0], 13)
  107. v1[0] ^= v0[0]
  108. v0[0] = _rotl(v0[0], 32)
  109. v2[0] += v3[0]
  110. v3[0] = _rotl(v3[0], 16)
  111. v3[0] ^= v2[0]
  112. v0[0] += v3[0]
  113. v3[0] = _rotl(v3[0], 21)
  114. v3[0] ^= v0[0]
  115. v2[0] += v1[0]
  116. v1[0] = _rotl(v1[0], 17)
  117. v1[0] ^= v2[0]
  118. v2[0] = _rotl(v2[0], 32)
  119. @cython.cdivision(True)
  120. cdef uint64_t low_level_siphash(uint8_t* data, size_t datalen,
  121. uint8_t* key) nogil:
  122. cdef uint64_t v0 = 0x736f6d6570736575ULL
  123. cdef uint64_t v1 = 0x646f72616e646f6dULL
  124. cdef uint64_t v2 = 0x6c7967656e657261ULL
  125. cdef uint64_t v3 = 0x7465646279746573ULL
  126. cdef uint64_t b
  127. cdef uint64_t k0 = u8to64_le(key)
  128. cdef uint64_t k1 = u8to64_le(key + 8)
  129. cdef uint64_t m
  130. cdef int i
  131. cdef uint8_t* end = data + datalen - (datalen % sizeof(uint64_t))
  132. cdef int left = datalen & 7
  133. cdef int cROUNDS = 2
  134. cdef int dROUNDS = 4
  135. b = (<uint64_t>datalen) << 56
  136. v3 ^= k1
  137. v2 ^= k0
  138. v1 ^= k1
  139. v0 ^= k0
  140. while (data != end):
  141. m = u8to64_le(data)
  142. v3 ^= m
  143. for i in range(cROUNDS):
  144. _sipround(&v0, &v1, &v2, &v3)
  145. v0 ^= m
  146. data += sizeof(uint64_t)
  147. for i in range(left-1, -1, -1):
  148. b |= (<uint64_t>data[i]) << (i * 8)
  149. v3 ^= b
  150. for i in range(cROUNDS):
  151. _sipround(&v0, &v1, &v2, &v3)
  152. v0 ^= b
  153. v2 ^= 0xff
  154. for i in range(dROUNDS):
  155. _sipround(&v0, &v1, &v2, &v3)
  156. b = v0 ^ v1 ^ v2 ^ v3
  157. return b