Hashtable.hpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /*
  2. * Copyright (c)2019 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: 2026-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 <stdint.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <stdexcept>
  20. #include <vector>
  21. #include <utility>
  22. #include <algorithm>
  23. namespace ZeroTier {
  24. /**
  25. * A minimal hash table implementation for the ZeroTier core
  26. */
  27. template<typename K,typename V>
  28. class Hashtable
  29. {
  30. private:
  31. struct _Bucket
  32. {
  33. _Bucket(const K &k,const V &v) : k(k),v(v) {}
  34. _Bucket(const K &k) : k(k),v() {}
  35. _Bucket(const _Bucket &b) : k(b.k),v(b.v) {}
  36. inline _Bucket &operator=(const _Bucket &b) { k = b.k; v = b.v; return *this; }
  37. K k;
  38. V v;
  39. _Bucket *next; // must be set manually for each _Bucket
  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. Iterator(Hashtable &ht) :
  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. inline bool next(K *&kptr,V *&vptr)
  67. {
  68. for(;;) {
  69. if (_b) {
  70. kptr = &(_b->k);
  71. vptr = &(_b->v);
  72. _b = _b->next;
  73. return true;
  74. }
  75. ++_idx;
  76. if (_idx >= _ht->_bc) {
  77. return false;
  78. }
  79. _b = _ht->_t[_idx];
  80. }
  81. }
  82. private:
  83. unsigned long _idx;
  84. Hashtable *_ht;
  85. _Bucket *_b;
  86. };
  87. //friend class Hashtable<K,V>::Iterator;
  88. /**
  89. * @param bc Initial capacity in buckets (default: 64, must be nonzero)
  90. */
  91. Hashtable(unsigned long bc = 64) :
  92. _t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * bc))),
  93. _bc(bc),
  94. _s(0)
  95. {
  96. if (!_t) {
  97. throw ZT_EXCEPTION_OUT_OF_MEMORY;
  98. }
  99. for(unsigned long i=0;i<bc;++i) {
  100. _t[i] = (_Bucket *)0;
  101. }
  102. }
  103. Hashtable(const Hashtable<K,V> &ht) :
  104. _t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * ht._bc))),
  105. _bc(ht._bc),
  106. _s(ht._s)
  107. {
  108. if (!_t) {
  109. throw ZT_EXCEPTION_OUT_OF_MEMORY;
  110. }
  111. for(unsigned long i=0;i<_bc;++i) {
  112. _t[i] = (_Bucket *)0;
  113. }
  114. for(unsigned long i=0;i<_bc;++i) {
  115. const _Bucket *b = ht._t[i];
  116. while (b) {
  117. _Bucket *nb = new _Bucket(*b);
  118. nb->next = _t[i];
  119. _t[i] = nb;
  120. b = b->next;
  121. }
  122. }
  123. }
  124. ~Hashtable()
  125. {
  126. this->clear();
  127. ::free(_t);
  128. }
  129. inline Hashtable &operator=(const Hashtable<K,V> &ht)
  130. {
  131. this->clear();
  132. if (ht._s) {
  133. for(unsigned long i=0;i<ht._bc;++i) {
  134. const _Bucket *b = ht._t[i];
  135. while (b) {
  136. this->set(b->k,b->v);
  137. b = b->next;
  138. }
  139. }
  140. }
  141. return *this;
  142. }
  143. /**
  144. * Erase all entries
  145. */
  146. inline void clear()
  147. {
  148. if (_s) {
  149. for(unsigned long i=0;i<_bc;++i) {
  150. _Bucket *b = _t[i];
  151. while (b) {
  152. _Bucket *const nb = b->next;
  153. delete b;
  154. b = nb;
  155. }
  156. _t[i] = (_Bucket *)0;
  157. }
  158. _s = 0;
  159. }
  160. }
  161. /**
  162. * @return Vector of all keys
  163. */
  164. inline typename std::vector<K> keys() const
  165. {
  166. typename std::vector<K> k;
  167. if (_s) {
  168. k.reserve(_s);
  169. for(unsigned long i=0;i<_bc;++i) {
  170. _Bucket *b = _t[i];
  171. while (b) {
  172. k.push_back(b->k);
  173. b = b->next;
  174. }
  175. }
  176. }
  177. return k;
  178. }
  179. /**
  180. * Append all keys (in unspecified order) to the supplied vector or list
  181. *
  182. * @param v Vector, list, or other compliant container
  183. * @tparam Type of V (generally inferred)
  184. */
  185. template<typename C>
  186. inline void appendKeys(C &v) const
  187. {
  188. if (_s) {
  189. for(unsigned long i=0;i<_bc;++i) {
  190. _Bucket *b = _t[i];
  191. while (b) {
  192. v.push_back(b->k);
  193. b = b->next;
  194. }
  195. }
  196. }
  197. }
  198. /**
  199. * @return Vector of all entries (pairs of K,V)
  200. */
  201. inline typename std::vector< std::pair<K,V> > entries() const
  202. {
  203. typename std::vector< std::pair<K,V> > k;
  204. if (_s) {
  205. k.reserve(_s);
  206. for(unsigned long i=0;i<_bc;++i) {
  207. _Bucket *b = _t[i];
  208. while (b) {
  209. k.push_back(std::pair<K,V>(b->k,b->v));
  210. b = b->next;
  211. }
  212. }
  213. }
  214. return k;
  215. }
  216. /**
  217. * @param k Key
  218. * @return Pointer to value or NULL if not found
  219. */
  220. inline V *get(const K &k)
  221. {
  222. _Bucket *b = _t[_hc(k) % _bc];
  223. while (b) {
  224. if (b->k == k) {
  225. return &(b->v);
  226. }
  227. b = b->next;
  228. }
  229. return (V *)0;
  230. }
  231. inline const V *get(const K &k) const { return const_cast<Hashtable *>(this)->get(k); }
  232. /**
  233. * @param k Key
  234. * @param v Value to fill with result
  235. * @return True if value was found and set (if false, v is not modified)
  236. */
  237. inline bool get(const K &k,V &v) const
  238. {
  239. _Bucket *b = _t[_hc(k) % _bc];
  240. while (b) {
  241. if (b->k == k) {
  242. v = b->v;
  243. return true;
  244. }
  245. b = b->next;
  246. }
  247. return false;
  248. }
  249. /**
  250. * @param k Key to check
  251. * @return True if key is present
  252. */
  253. inline bool contains(const K &k) const
  254. {
  255. _Bucket *b = _t[_hc(k) % _bc];
  256. while (b) {
  257. if (b->k == k) {
  258. return true;
  259. }
  260. b = b->next;
  261. }
  262. return false;
  263. }
  264. /**
  265. * @param k Key
  266. * @return True if value was present
  267. */
  268. inline bool erase(const K &k)
  269. {
  270. const unsigned long bidx = _hc(k) % _bc;
  271. _Bucket *lastb = (_Bucket *)0;
  272. _Bucket *b = _t[bidx];
  273. while (b) {
  274. if (b->k == k) {
  275. if (lastb) {
  276. lastb->next = b->next;
  277. } else {
  278. _t[bidx] = b->next;
  279. }
  280. delete b;
  281. --_s;
  282. return true;
  283. }
  284. lastb = b;
  285. b = b->next;
  286. }
  287. return false;
  288. }
  289. /**
  290. * @param k Key
  291. * @param v Value
  292. * @return Reference to value in table
  293. */
  294. inline V &set(const K &k,const V &v)
  295. {
  296. const unsigned long h = _hc(k);
  297. unsigned long bidx = h % _bc;
  298. _Bucket *b = _t[bidx];
  299. while (b) {
  300. if (b->k == k) {
  301. b->v = v;
  302. return b->v;
  303. }
  304. b = b->next;
  305. }
  306. if (_s >= _bc) {
  307. _grow();
  308. bidx = h % _bc;
  309. }
  310. b = new _Bucket(k,v);
  311. b->next = _t[bidx];
  312. _t[bidx] = b;
  313. ++_s;
  314. return b->v;
  315. }
  316. /**
  317. * @param k Key
  318. * @return Value, possibly newly created
  319. */
  320. inline V &operator[](const K &k)
  321. {
  322. const unsigned long h = _hc(k);
  323. unsigned long bidx = h % _bc;
  324. _Bucket *b = _t[bidx];
  325. while (b) {
  326. if (b->k == k) {
  327. return b->v;
  328. }
  329. b = b->next;
  330. }
  331. if (_s >= _bc) {
  332. _grow();
  333. bidx = h % _bc;
  334. }
  335. b = new _Bucket(k);
  336. b->next = _t[bidx];
  337. _t[bidx] = b;
  338. ++_s;
  339. return b->v;
  340. }
  341. /**
  342. * @return Number of entries
  343. */
  344. inline unsigned long size() const { return _s; }
  345. /**
  346. * @return True if table is empty
  347. */
  348. inline bool empty() const { return (_s == 0); }
  349. private:
  350. template<typename O>
  351. static inline unsigned long _hc(const O &obj)
  352. {
  353. return (unsigned long)obj.hashCode();
  354. }
  355. static inline unsigned long _hc(const uint64_t i)
  356. {
  357. return (unsigned long)(i ^ (i >> 32)); // good for network IDs and addresses
  358. }
  359. static inline unsigned long _hc(const uint32_t i)
  360. {
  361. return ((unsigned long)i * (unsigned long)0x9e3779b1);
  362. }
  363. static inline unsigned long _hc(const uint16_t i)
  364. {
  365. return ((unsigned long)i * (unsigned long)0x9e3779b1);
  366. }
  367. static inline unsigned long _hc(const int i)
  368. {
  369. return ((unsigned long)i * (unsigned long)0x9e3379b1);
  370. }
  371. inline void _grow()
  372. {
  373. const unsigned long nc = _bc * 2;
  374. _Bucket **nt = reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * nc));
  375. if (nt) {
  376. for(unsigned long i=0;i<nc;++i) {
  377. nt[i] = (_Bucket *)0;
  378. }
  379. for(unsigned long i=0;i<_bc;++i) {
  380. _Bucket *b = _t[i];
  381. while (b) {
  382. _Bucket *const nb = b->next;
  383. const unsigned long nidx = _hc(b->k) % nc;
  384. b->next = nt[nidx];
  385. nt[nidx] = b;
  386. b = nb;
  387. }
  388. }
  389. ::free(_t);
  390. _t = nt;
  391. _bc = nc;
  392. }
  393. }
  394. _Bucket **_t;
  395. unsigned long _bc;
  396. unsigned long _s;
  397. };
  398. } // namespace ZeroTier
  399. #endif