hashindex.pyx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # -*- coding: utf-8 -*-
  2. import os
  3. cimport cython
  4. from libc.stdint cimport uint32_t, UINT32_MAX, uint64_t
  5. API_VERSION = 2
  6. cdef extern from "_hashindex.c":
  7. ctypedef struct HashIndex:
  8. pass
  9. HashIndex *hashindex_read(char *path)
  10. HashIndex *hashindex_init(int capacity, int key_size, int value_size)
  11. void hashindex_free(HashIndex *index)
  12. int hashindex_get_size(HashIndex *index)
  13. int hashindex_write(HashIndex *index, char *path)
  14. void *hashindex_get(HashIndex *index, void *key)
  15. void *hashindex_next_key(HashIndex *index, void *key)
  16. int hashindex_delete(HashIndex *index, void *key)
  17. int hashindex_set(HashIndex *index, void *key, void *value)
  18. uint32_t _htole32(uint32_t v)
  19. uint32_t _le32toh(uint32_t v)
  20. cdef _NoDefault = object()
  21. """
  22. The HashIndex is *not* a general purpose data structure. The value size must be at least 4 bytes, and these
  23. first bytes are used for in-band signalling in the data structure itself.
  24. The constant MAX_VALUE defines the valid range for these 4 bytes when interpreted as an uint32_t from 0
  25. to MAX_VALUE (inclusive). The following reserved values beyond MAX_VALUE are currently in use
  26. (byte order is LE)::
  27. 0xffffffff marks empty entries in the hashtable
  28. 0xfffffffe marks deleted entries in the hashtable
  29. None of the publicly available classes in this module will accept nor return a reserved value;
  30. AssertionError is raised instead.
  31. """
  32. assert UINT32_MAX == 2**32-1
  33. # module-level constant because cdef's in classes can't have default values
  34. cdef uint32_t _MAX_VALUE = 2**32-1025
  35. MAX_VALUE = _MAX_VALUE
  36. assert _MAX_VALUE % 2 == 1
  37. @cython.internal
  38. cdef class IndexBase:
  39. cdef HashIndex *index
  40. cdef int key_size
  41. def __cinit__(self, capacity=0, path=None, key_size=32):
  42. self.key_size = key_size
  43. if path:
  44. path = os.fsencode(path)
  45. self.index = hashindex_read(path)
  46. if not self.index:
  47. raise Exception('hashindex_read failed')
  48. else:
  49. self.index = hashindex_init(capacity, self.key_size, self.value_size)
  50. if not self.index:
  51. raise Exception('hashindex_init failed')
  52. def __dealloc__(self):
  53. if self.index:
  54. hashindex_free(self.index)
  55. @classmethod
  56. def read(cls, path):
  57. return cls(path=path)
  58. def write(self, path):
  59. path = os.fsencode(path)
  60. if not hashindex_write(self.index, path):
  61. raise Exception('hashindex_write failed')
  62. def clear(self):
  63. hashindex_free(self.index)
  64. self.index = hashindex_init(0, self.key_size, self.value_size)
  65. if not self.index:
  66. raise Exception('hashindex_init failed')
  67. def setdefault(self, key, value):
  68. if not key in self:
  69. self[key] = value
  70. def __delitem__(self, key):
  71. assert len(key) == self.key_size
  72. if not hashindex_delete(self.index, <char *>key):
  73. raise Exception('hashindex_delete failed')
  74. def get(self, key, default=None):
  75. try:
  76. return self[key]
  77. except KeyError:
  78. return default
  79. def pop(self, key, default=_NoDefault):
  80. try:
  81. value = self[key]
  82. del self[key]
  83. return value
  84. except KeyError:
  85. if default != _NoDefault:
  86. return default
  87. raise
  88. def __len__(self):
  89. return hashindex_get_size(self.index)
  90. cdef class NSIndex(IndexBase):
  91. value_size = 8
  92. def __getitem__(self, key):
  93. assert len(key) == self.key_size
  94. data = <uint32_t *>hashindex_get(self.index, <char *>key)
  95. if not data:
  96. raise KeyError(key)
  97. cdef uint32_t segment = _le32toh(data[0])
  98. assert segment <= _MAX_VALUE, "maximum number of segments reached"
  99. return segment, _le32toh(data[1])
  100. def __setitem__(self, key, value):
  101. assert len(key) == self.key_size
  102. cdef uint32_t[2] data
  103. cdef uint32_t segment = value[0]
  104. assert segment <= _MAX_VALUE, "maximum number of segments reached"
  105. data[0] = _htole32(segment)
  106. data[1] = _htole32(value[1])
  107. if not hashindex_set(self.index, <char *>key, data):
  108. raise Exception('hashindex_set failed')
  109. def __contains__(self, key):
  110. cdef uint32_t segment
  111. assert len(key) == self.key_size
  112. data = <uint32_t *>hashindex_get(self.index, <char *>key)
  113. if data != NULL:
  114. segment = _le32toh(data[0])
  115. assert segment <= _MAX_VALUE, "maximum number of segments reached"
  116. return data != NULL
  117. def iteritems(self, marker=None):
  118. cdef const void *key
  119. iter = NSKeyIterator(self.key_size)
  120. iter.idx = self
  121. iter.index = self.index
  122. if marker:
  123. key = hashindex_get(self.index, <char *>marker)
  124. if marker is None:
  125. raise IndexError
  126. iter.key = key - self.key_size
  127. return iter
  128. cdef class NSKeyIterator:
  129. cdef NSIndex idx
  130. cdef HashIndex *index
  131. cdef const void *key
  132. cdef int key_size
  133. def __cinit__(self, key_size):
  134. self.key = NULL
  135. self.key_size = key_size
  136. def __iter__(self):
  137. return self
  138. def __next__(self):
  139. self.key = hashindex_next_key(self.index, <char *>self.key)
  140. if not self.key:
  141. raise StopIteration
  142. cdef uint32_t *value = <uint32_t *>(self.key + self.key_size)
  143. cdef uint32_t segment = _le32toh(value[0])
  144. assert segment <= _MAX_VALUE, "maximum number of segments reached"
  145. return (<char *>self.key)[:self.key_size], (segment, _le32toh(value[1]))
  146. cdef class ChunkIndex(IndexBase):
  147. """
  148. Mapping of 32 byte keys to (refcount, size, csize), which are all 32-bit unsigned.
  149. The reference count cannot overflow. If an overflow would occur, the refcount
  150. is fixed to MAX_VALUE and will neither increase nor decrease by incref(), decref()
  151. or add().
  152. Prior signed 32-bit overflow is handled correctly for most cases: All values
  153. from UINT32_MAX (2**32-1, inclusive) to MAX_VALUE (exclusive) are reserved and either
  154. cause silent data loss (-1, -2) or will raise an AssertionError when accessed.
  155. Other values are handled correctly. Note that previously the refcount could also reach
  156. 0 by *increasing* it.
  157. Assigning refcounts in this reserved range is an invalid operation and raises AssertionError.
  158. """
  159. value_size = 12
  160. def __getitem__(self, key):
  161. assert len(key) == self.key_size
  162. data = <uint32_t *>hashindex_get(self.index, <char *>key)
  163. if not data:
  164. raise KeyError(key)
  165. cdef uint32_t refcount = _le32toh(data[0])
  166. assert refcount <= _MAX_VALUE
  167. return refcount, _le32toh(data[1]), _le32toh(data[2])
  168. def __setitem__(self, key, value):
  169. assert len(key) == self.key_size
  170. cdef uint32_t[3] data
  171. cdef uint32_t refcount = value[0]
  172. assert refcount <= _MAX_VALUE, "invalid reference count"
  173. data[0] = _htole32(refcount)
  174. data[1] = _htole32(value[1])
  175. data[2] = _htole32(value[2])
  176. if not hashindex_set(self.index, <char *>key, data):
  177. raise Exception('hashindex_set failed')
  178. def __contains__(self, key):
  179. assert len(key) == self.key_size
  180. data = <uint32_t *>hashindex_get(self.index, <char *>key)
  181. if data != NULL:
  182. assert data[0] <= _MAX_VALUE
  183. return data != NULL
  184. def incref(self, key):
  185. """Increase refcount for 'key', return (refcount, size, csize)"""
  186. assert len(key) == self.key_size
  187. data = <uint32_t *>hashindex_get(self.index, <char *>key)
  188. if not data:
  189. raise KeyError(key)
  190. cdef uint32_t refcount = _le32toh(data[0])
  191. assert refcount <= _MAX_VALUE, "invalid reference count"
  192. if refcount != _MAX_VALUE:
  193. refcount += 1
  194. data[0] = _htole32(refcount)
  195. return refcount, _le32toh(data[1]), _le32toh(data[2])
  196. def decref(self, key):
  197. """Decrease refcount for 'key', return (refcount, size, csize)"""
  198. assert len(key) == self.key_size
  199. data = <uint32_t *>hashindex_get(self.index, <char *>key)
  200. if not data:
  201. raise KeyError(key)
  202. cdef uint32_t refcount = _le32toh(data[0])
  203. # Never decrease a reference count of zero
  204. assert 0 < refcount <= _MAX_VALUE, "invalid reference count"
  205. if refcount != _MAX_VALUE:
  206. refcount -= 1
  207. data[0] = _htole32(refcount)
  208. return refcount, _le32toh(data[1]), _le32toh(data[2])
  209. def iteritems(self, marker=None):
  210. cdef const void *key
  211. iter = ChunkKeyIterator(self.key_size)
  212. iter.idx = self
  213. iter.index = self.index
  214. if marker:
  215. key = hashindex_get(self.index, <char *>marker)
  216. if marker is None:
  217. raise IndexError
  218. iter.key = key - self.key_size
  219. return iter
  220. def summarize(self):
  221. cdef uint64_t size = 0, csize = 0, unique_size = 0, unique_csize = 0, chunks = 0, unique_chunks = 0
  222. cdef uint32_t *values
  223. cdef uint32_t refcount
  224. cdef void *key = NULL
  225. while True:
  226. key = hashindex_next_key(self.index, key)
  227. if not key:
  228. break
  229. unique_chunks += 1
  230. values = <uint32_t*> (key + self.key_size)
  231. refcount = _le32toh(values[0])
  232. assert refcount <= MAX_VALUE, "invalid reference count"
  233. chunks += refcount
  234. unique_size += _le32toh(values[1])
  235. unique_csize += _le32toh(values[2])
  236. size += <uint64_t> _le32toh(values[1]) * _le32toh(values[0])
  237. csize += <uint64_t> _le32toh(values[2]) * _le32toh(values[0])
  238. return size, csize, unique_size, unique_csize, unique_chunks, chunks
  239. def add(self, key, refs, size, csize):
  240. assert len(key) == self.key_size
  241. cdef uint32_t[3] data
  242. data[0] = _htole32(refs)
  243. data[1] = _htole32(size)
  244. data[2] = _htole32(csize)
  245. self._add(<char*> key, data)
  246. cdef _add(self, void *key, uint32_t *data):
  247. cdef uint64_t refcount1, refcount2, result64
  248. values = <uint32_t*> hashindex_get(self.index, key)
  249. if values:
  250. refcount1 = _le32toh(values[0])
  251. refcount2 = _le32toh(data[0])
  252. assert refcount1 <= _MAX_VALUE
  253. assert refcount2 <= _MAX_VALUE
  254. result64 = refcount1 + refcount2
  255. values[0] = _htole32(min(result64, _MAX_VALUE))
  256. else:
  257. if not hashindex_set(self.index, key, data):
  258. raise Exception('hashindex_set failed')
  259. def merge(self, ChunkIndex other):
  260. cdef void *key = NULL
  261. while True:
  262. key = hashindex_next_key(other.index, key)
  263. if not key:
  264. break
  265. self._add(key, <uint32_t*> (key + self.key_size))
  266. cdef class ChunkKeyIterator:
  267. cdef ChunkIndex idx
  268. cdef HashIndex *index
  269. cdef const void *key
  270. cdef int key_size
  271. def __cinit__(self, key_size):
  272. self.key = NULL
  273. self.key_size = key_size
  274. def __iter__(self):
  275. return self
  276. def __next__(self):
  277. self.key = hashindex_next_key(self.index, <char *>self.key)
  278. if not self.key:
  279. raise StopIteration
  280. cdef uint32_t *value = <uint32_t *>(self.key + self.key_size)
  281. cdef uint32_t refcount = _le32toh(value[0])
  282. assert refcount <= MAX_VALUE, "invalid reference count"
  283. return (<char *>self.key)[:self.key_size], (refcount, _le32toh(value[1]), _le32toh(value[2]))