Hashtable.hpp 7.8 KB

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