Hashtable.hpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_HASHTABLE_HPP
  14. #define ZT_HASHTABLE_HPP
  15. #include "Constants.hpp"
  16. #include "Utils.hpp"
  17. #include <cstdlib>
  18. #include <cstring>
  19. #include <stdexcept>
  20. #include <vector>
  21. namespace ZeroTier {
  22. /**
  23. * A minimal hash table implementation for the ZeroTier core
  24. *
  25. * This is optimized for smaller data sets.
  26. */
  27. template<typename K,typename V>
  28. class Hashtable
  29. {
  30. private:
  31. struct _Bucket
  32. {
  33. ZT_INLINE _Bucket(const K &k,const V &v) : k(k),v(v) {}
  34. explicit ZT_INLINE _Bucket(const K &k) : k(k),v() {}
  35. ZT_INLINE _Bucket(const _Bucket &b) : k(b.k),v(b.v) {}
  36. ZT_INLINE _Bucket &operator=(const _Bucket &b) { k = b.k; v = b.v; return *this; }
  37. _Bucket *next; // must be set manually for each _Bucket
  38. const K k;
  39. V v;
  40. };
  41. public:
  42. /**
  43. * A simple forward iterator (different from STL)
  44. *
  45. * It's safe to erase the last key, but not others. Don't use set() since that
  46. * may rehash and invalidate the iterator. Note the erasing the key will destroy
  47. * the targets of the pointers returned by next().
  48. */
  49. class Iterator
  50. {
  51. public:
  52. /**
  53. * @param ht Hash table to iterate over
  54. */
  55. explicit ZT_INLINE Iterator(Hashtable &ht) noexcept :
  56. _idx(0),
  57. _ht(&ht),
  58. _b(ht._t[0])
  59. {
  60. }
  61. /**
  62. * @param kptr Pointer to set to point to next key
  63. * @param vptr Pointer to set to point to next value
  64. * @return True if kptr and vptr are set, false if no more entries
  65. */
  66. ZT_INLINE bool next(K *&kptr,V *&vptr)
  67. {
  68. for(;;) {
  69. if (_b) {
  70. kptr = (K *)(&(_b->k));
  71. vptr = (V *)(&(_b->v));
  72. _b = _b->next;
  73. return true;
  74. }
  75. ++_idx;
  76. if (_idx >= _ht->_bc)
  77. return false;
  78. _b = _ht->_t[_idx];
  79. }
  80. }
  81. private:
  82. unsigned long _idx;
  83. Hashtable *_ht;
  84. _Bucket *_b;
  85. };
  86. //friend class Hashtable<K,V>::Iterator;
  87. /**
  88. * @param bc Initial capacity in buckets (default: 32, must be nonzero)
  89. */
  90. explicit ZT_INLINE Hashtable(unsigned int bc = 32) :
  91. _t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * bc))),
  92. _bc(bc),
  93. _s(0)
  94. {
  95. if (!_t)
  96. throw std::bad_alloc();
  97. Utils::zero(_t,sizeof(uintptr_t) * bc);
  98. }
  99. ZT_INLINE Hashtable(const Hashtable<K,V> &ht) :
  100. Hashtable()
  101. {
  102. *this = ht;
  103. }
  104. ZT_INLINE ~Hashtable()
  105. {
  106. this->clear();
  107. ::free(_t);
  108. }
  109. ZT_INLINE Hashtable &operator=(const Hashtable<K,V> &ht)
  110. {
  111. this->clear();
  112. if (ht._s) {
  113. for(unsigned long i=0;i<ht._bc;++i) {
  114. const _Bucket *b = ht._t[i];
  115. while (b) {
  116. this->set(b->k,b->v);
  117. b = b->next;
  118. }
  119. }
  120. }
  121. return *this;
  122. }
  123. /**
  124. * Erase all entries
  125. */
  126. ZT_INLINE void clear()
  127. {
  128. if (_s) {
  129. for(unsigned long i=0;i<_bc;++i) {
  130. _Bucket *b = _t[i];
  131. while (b) {
  132. _Bucket *const nb = b->next;
  133. delete b;
  134. b = nb;
  135. }
  136. _t[i] = (_Bucket *)0;
  137. }
  138. _s = 0;
  139. }
  140. }
  141. /**
  142. * @return Vector of all keys
  143. */
  144. ZT_INLINE typename std::vector<K> keys() const
  145. {
  146. typename std::vector<K> k;
  147. if (_s) {
  148. k.reserve(_s);
  149. for(unsigned long i=0;i<_bc;++i) {
  150. _Bucket *b = _t[i];
  151. while (b) {
  152. k.push_back(b->k);
  153. b = b->next;
  154. }
  155. }
  156. }
  157. return k;
  158. }
  159. /**
  160. * Append all keys (in unspecified order) to the supplied vector or list
  161. *
  162. * @param v Vector, list, or other compliant container
  163. * @tparam Type of V (generally inferred)
  164. */
  165. template<typename C>
  166. ZT_INLINE void appendKeys(C &v) const
  167. {
  168. if (_s) {
  169. for(unsigned long i=0;i<_bc;++i) {
  170. _Bucket *b = _t[i];
  171. while (b) {
  172. v.push_back(b->k);
  173. b = b->next;
  174. }
  175. }
  176. }
  177. }
  178. /**
  179. * @return Vector of all entries (pairs of K,V)
  180. */
  181. ZT_INLINE typename std::vector< std::pair<K,V> > entries() const
  182. {
  183. typename std::vector< std::pair<K,V> > k;
  184. if (_s) {
  185. k.reserve(_s);
  186. for(unsigned long i=0;i<_bc;++i) {
  187. _Bucket *b = _t[i];
  188. while (b) {
  189. k.push_back(std::pair<K,V>(b->k,b->v));
  190. b = b->next;
  191. }
  192. }
  193. }
  194. return k;
  195. }
  196. /**
  197. * @param k Key
  198. * @return Pointer to value or NULL if not found
  199. */
  200. ZT_INLINE V *get(const K k)
  201. {
  202. _Bucket *b = _t[_hc(k) % _bc];
  203. while (b) {
  204. if (b->k == k)
  205. return &(b->v);
  206. b = b->next;
  207. }
  208. return (V *)0;
  209. }
  210. ZT_INLINE const V *get(const K k) const { return const_cast<Hashtable *>(this)->get(k); }
  211. /**
  212. * @param k Key
  213. * @param v Value to fill with result
  214. * @return True if value was found and set (if false, v is not modified)
  215. */
  216. ZT_INLINE bool get(const K &k,V &v) const
  217. {
  218. _Bucket *b = _t[_hc(k) % _bc];
  219. while (b) {
  220. if (b->k == k) {
  221. v = b->v;
  222. return true;
  223. }
  224. b = b->next;
  225. }
  226. return false;
  227. }
  228. /**
  229. * @param k Key to check
  230. * @return True if key is present
  231. */
  232. ZT_INLINE bool contains(const K &k) const
  233. {
  234. _Bucket *b = _t[_hc(k) % _bc];
  235. while (b) {
  236. if (b->k == k)
  237. return true;
  238. b = b->next;
  239. }
  240. return false;
  241. }
  242. /**
  243. * @param k Key
  244. * @return True if value was present
  245. */
  246. ZT_INLINE bool erase(const K &k)
  247. {
  248. const unsigned long bidx = _hc(k) % _bc;
  249. _Bucket *lastb = (_Bucket *)0;
  250. _Bucket *b = _t[bidx];
  251. while (b) {
  252. if (b->k == k) {
  253. if (lastb)
  254. lastb->next = b->next;
  255. else _t[bidx] = b->next;
  256. delete b;
  257. --_s;
  258. return true;
  259. }
  260. lastb = b;
  261. b = b->next;
  262. }
  263. return false;
  264. }
  265. /**
  266. * @param k Key
  267. * @param v Value
  268. * @return Reference to value in table
  269. */
  270. ZT_INLINE V &set(const K &k,const V &v)
  271. {
  272. const unsigned long h = _hc(k);
  273. unsigned long bidx = h % _bc;
  274. _Bucket *b = _t[bidx];
  275. while (b) {
  276. if (b->k == k) {
  277. b->v = v;
  278. return b->v;
  279. }
  280. b = b->next;
  281. }
  282. if (_s >= _bc) {
  283. _grow();
  284. bidx = h % _bc;
  285. }
  286. b = new _Bucket(k,v);
  287. b->next = _t[bidx];
  288. _t[bidx] = b;
  289. ++_s;
  290. return b->v;
  291. }
  292. /**
  293. * @param k Key
  294. * @return Value, possibly newly created
  295. */
  296. ZT_INLINE V &operator[](const K k)
  297. {
  298. const unsigned long h = _hc(k);
  299. unsigned long bidx = h % _bc;
  300. _Bucket *b = _t[bidx];
  301. while (b) {
  302. if (b->k == k)
  303. return b->v;
  304. b = b->next;
  305. }
  306. if (_s >= _bc) {
  307. _grow();
  308. bidx = h % _bc;
  309. }
  310. b = new _Bucket(k);
  311. b->next = _t[bidx];
  312. _t[bidx] = b;
  313. ++_s;
  314. return b->v;
  315. }
  316. /**
  317. * @return Number of entries
  318. */
  319. ZT_INLINE unsigned long size() const noexcept { return _s; }
  320. /**
  321. * @return True if table is empty
  322. */
  323. ZT_INLINE bool empty() const noexcept { return (_s == 0); }
  324. private:
  325. template<typename O>
  326. static ZT_INLINE unsigned long _hc(const O &obj) { return (unsigned long)obj.hashCode(); }
  327. static ZT_INLINE unsigned long _hc(const uint64_t i) noexcept { return (unsigned long)(i + (i >> 32U)); }
  328. static ZT_INLINE unsigned long _hc(const uint32_t i) noexcept { return ((unsigned long)i * (unsigned long)0x9e3779b1); }
  329. static ZT_INLINE unsigned long _hc(const uint16_t i) noexcept { return ((unsigned long)i * (unsigned long)0x9e3779b1); }
  330. static ZT_INLINE unsigned long _hc(const uint8_t i) noexcept { return ((unsigned long)i * (unsigned long)0x9e3779b1); }
  331. static ZT_INLINE unsigned long _hc(const int64_t i) noexcept { return (unsigned long)((unsigned long long)i + ((unsigned long long)i >> 32U)); }
  332. static ZT_INLINE unsigned long _hc(const int32_t i) noexcept { return ((unsigned long)i * (unsigned long)0x9e3779b1); }
  333. static ZT_INLINE unsigned long _hc(const int16_t i) noexcept { return ((unsigned long)i * (unsigned long)0x9e3779b1); }
  334. static ZT_INLINE unsigned long _hc(const int8_t i) noexcept { return ((unsigned long)i * (unsigned long)0x9e3779b1); }
  335. static ZT_INLINE unsigned long _hc(void *p) noexcept { return ((unsigned long)((uintptr_t)p) * (unsigned long)0x9e3779b1); }
  336. static ZT_INLINE unsigned long _hc(const void *p) noexcept { return ((unsigned long)((uintptr_t)p) * (unsigned long)0x9e3779b1); }
  337. ZT_INLINE void _grow()
  338. {
  339. const unsigned long nc = _bc * 2;
  340. _Bucket **nt = reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * nc));
  341. if (nt) {
  342. for(unsigned long i=0;i<nc;++i)
  343. nt[i] = (_Bucket *)0;
  344. for(unsigned long i=0;i<_bc;++i) {
  345. _Bucket *b = _t[i];
  346. while (b) {
  347. _Bucket *const nb = b->next;
  348. const unsigned long nidx = _hc(b->k) % nc;
  349. b->next = nt[nidx];
  350. nt[nidx] = b;
  351. b = nb;
  352. }
  353. }
  354. ::free(_t);
  355. _t = nt;
  356. _bc = nc;
  357. }
  358. }
  359. _Bucket **_t;
  360. unsigned long _bc;
  361. unsigned long _s;
  362. };
  363. } // namespace ZeroTier
  364. #endif