Hashtable.hpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_HASHTABLE_HPP
  27. #define ZT_HASHTABLE_HPP
  28. #include "Constants.hpp"
  29. #include <stdint.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <stdexcept>
  33. #include <vector>
  34. #include <utility>
  35. #include <algorithm>
  36. namespace ZeroTier {
  37. /**
  38. * A minimal hash table implementation for the ZeroTier core
  39. *
  40. * This is not a drop-in replacement for STL containers, and has several
  41. * limitations. Keys can be uint64_t or an object, and if the latter they
  42. * must implement a method called hashCode() that returns an unsigned long
  43. * value that is evenly distributed.
  44. */
  45. template<typename K,typename V>
  46. class Hashtable
  47. {
  48. private:
  49. struct _Bucket
  50. {
  51. _Bucket(const K &k,const V &v) : k(k),v(v) {}
  52. _Bucket(const K &k) : k(k),v() {}
  53. _Bucket(const _Bucket &b) : k(b.k),v(b.v) {}
  54. inline _Bucket &operator=(const _Bucket &b) { k = b.k; v = b.v; return *this; }
  55. K k;
  56. V v;
  57. _Bucket *next; // must be set manually for each _Bucket
  58. };
  59. public:
  60. /**
  61. * A simple forward iterator (different from STL)
  62. *
  63. * It's safe to erase the last key, but not others. Don't use set() since that
  64. * may rehash and invalidate the iterator. Note the erasing the key will destroy
  65. * the targets of the pointers returned by next().
  66. */
  67. class Iterator
  68. {
  69. public:
  70. /**
  71. * @param ht Hash table to iterate over
  72. */
  73. Iterator(Hashtable &ht) :
  74. _idx(0),
  75. _ht(&ht),
  76. _b(ht._t[0])
  77. {
  78. }
  79. /**
  80. * @param kptr Pointer to set to point to next key
  81. * @param vptr Pointer to set to point to next value
  82. * @return True if kptr and vptr are set, false if no more entries
  83. */
  84. inline bool next(K *&kptr,V *&vptr)
  85. {
  86. for(;;) {
  87. if (_b) {
  88. kptr = &(_b->k);
  89. vptr = &(_b->v);
  90. _b = _b->next;
  91. return true;
  92. }
  93. ++_idx;
  94. if (_idx >= _ht->_bc)
  95. return false;
  96. _b = _ht->_t[_idx];
  97. }
  98. }
  99. private:
  100. unsigned long _idx;
  101. Hashtable *_ht;
  102. _Bucket *_b;
  103. };
  104. friend class Hashtable::Iterator;
  105. /**
  106. * @param bc Initial capacity in buckets (default: 64, must be nonzero)
  107. */
  108. Hashtable(unsigned long bc = 64) :
  109. _t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * bc))),
  110. _bc(bc),
  111. _s(0)
  112. {
  113. if (!_t)
  114. throw ZT_EXCEPTION_OUT_OF_MEMORY;
  115. for(unsigned long i=0;i<bc;++i)
  116. _t[i] = (_Bucket *)0;
  117. }
  118. Hashtable(const Hashtable<K,V> &ht) :
  119. _t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * ht._bc))),
  120. _bc(ht._bc),
  121. _s(ht._s)
  122. {
  123. if (!_t)
  124. throw ZT_EXCEPTION_OUT_OF_MEMORY;
  125. for(unsigned long i=0;i<_bc;++i)
  126. _t[i] = (_Bucket *)0;
  127. for(unsigned long i=0;i<_bc;++i) {
  128. const _Bucket *b = ht._t[i];
  129. while (b) {
  130. _Bucket *nb = new _Bucket(*b);
  131. nb->next = _t[i];
  132. _t[i] = nb;
  133. b = b->next;
  134. }
  135. }
  136. }
  137. ~Hashtable()
  138. {
  139. this->clear();
  140. ::free(_t);
  141. }
  142. inline Hashtable &operator=(const Hashtable<K,V> &ht)
  143. {
  144. this->clear();
  145. if (ht._s) {
  146. for(unsigned long i=0;i<ht._bc;++i) {
  147. const _Bucket *b = ht._t[i];
  148. while (b) {
  149. this->set(b->k,b->v);
  150. b = b->next;
  151. }
  152. }
  153. }
  154. return *this;
  155. }
  156. /**
  157. * Erase all entries
  158. */
  159. inline void clear()
  160. {
  161. if (_s) {
  162. for(unsigned long i=0;i<_bc;++i) {
  163. _Bucket *b = _t[i];
  164. while (b) {
  165. _Bucket *const nb = b->next;
  166. delete b;
  167. b = nb;
  168. }
  169. _t[i] = (_Bucket *)0;
  170. }
  171. _s = 0;
  172. }
  173. }
  174. /**
  175. * @return Vector of all keys
  176. */
  177. inline typename std::vector<K> keys() const
  178. {
  179. typename std::vector<K> k;
  180. if (_s) {
  181. k.reserve(_s);
  182. for(unsigned long i=0;i<_bc;++i) {
  183. _Bucket *b = _t[i];
  184. while (b) {
  185. k.push_back(b->k);
  186. b = b->next;
  187. }
  188. }
  189. }
  190. return k;
  191. }
  192. /**
  193. * Append all keys (in unspecified order) to the supplied vector or list
  194. *
  195. * @param v Vector, list, or other compliant container
  196. * @tparam Type of V (generally inferred)
  197. */
  198. template<typename C>
  199. inline void appendKeys(C &v) const
  200. {
  201. if (_s) {
  202. for(unsigned long i=0;i<_bc;++i) {
  203. _Bucket *b = _t[i];
  204. while (b) {
  205. v.push_back(b->k);
  206. b = b->next;
  207. }
  208. }
  209. }
  210. }
  211. /**
  212. * @return Vector of all entries (pairs of K,V)
  213. */
  214. inline typename std::vector< std::pair<K,V> > entries() const
  215. {
  216. typename std::vector< std::pair<K,V> > k;
  217. if (_s) {
  218. k.reserve(_s);
  219. for(unsigned long i=0;i<_bc;++i) {
  220. _Bucket *b = _t[i];
  221. while (b) {
  222. k.push_back(std::pair<K,V>(b->k,b->v));
  223. b = b->next;
  224. }
  225. }
  226. }
  227. return k;
  228. }
  229. /**
  230. * @param k Key
  231. * @return Pointer to value or NULL if not found
  232. */
  233. inline V *get(const K &k)
  234. {
  235. _Bucket *b = _t[_hc(k) % _bc];
  236. while (b) {
  237. if (b->k == k)
  238. return &(b->v);
  239. b = b->next;
  240. }
  241. return (V *)0;
  242. }
  243. inline const V *get(const K &k) const { return const_cast<Hashtable *>(this)->get(k); }
  244. /**
  245. * @param k Key to check
  246. * @return True if key is present
  247. */
  248. inline bool contains(const K &k) const
  249. {
  250. _Bucket *b = _t[_hc(k) % _bc];
  251. while (b) {
  252. if (b->k == k)
  253. return true;
  254. b = b->next;
  255. }
  256. return false;
  257. }
  258. /**
  259. * @param k Key
  260. * @return True if value was present
  261. */
  262. inline bool erase(const K &k)
  263. {
  264. const unsigned long bidx = _hc(k) % _bc;
  265. _Bucket *lastb = (_Bucket *)0;
  266. _Bucket *b = _t[bidx];
  267. while (b) {
  268. if (b->k == k) {
  269. if (lastb)
  270. lastb->next = b->next;
  271. else _t[bidx] = b->next;
  272. delete b;
  273. --_s;
  274. return true;
  275. }
  276. lastb = b;
  277. b = b->next;
  278. }
  279. return false;
  280. }
  281. /**
  282. * @param k Key
  283. * @param v Value
  284. * @return Reference to value in table
  285. */
  286. inline V &set(const K &k,const V &v)
  287. {
  288. const unsigned long h = _hc(k);
  289. unsigned long bidx = h % _bc;
  290. _Bucket *b = _t[bidx];
  291. while (b) {
  292. if (b->k == k) {
  293. b->v = v;
  294. return b->v;
  295. }
  296. b = b->next;
  297. }
  298. if (_s >= _bc) {
  299. _grow();
  300. bidx = h % _bc;
  301. }
  302. b = new _Bucket(k,v);
  303. b->next = _t[bidx];
  304. _t[bidx] = b;
  305. ++_s;
  306. return b->v;
  307. }
  308. /**
  309. * @param k Key
  310. * @return Value, possibly newly created
  311. */
  312. inline V &operator[](const K &k)
  313. {
  314. const unsigned long h = _hc(k);
  315. unsigned long bidx = h % _bc;
  316. _Bucket *b = _t[bidx];
  317. while (b) {
  318. if (b->k == k)
  319. return b->v;
  320. b = b->next;
  321. }
  322. if (_s >= _bc) {
  323. _grow();
  324. bidx = h % _bc;
  325. }
  326. b = new _Bucket(k);
  327. b->next = _t[bidx];
  328. _t[bidx] = b;
  329. ++_s;
  330. return b->v;
  331. }
  332. /**
  333. * @return Number of entries
  334. */
  335. inline unsigned long size() const { return _s; }
  336. /**
  337. * @return True if table is empty
  338. */
  339. inline bool empty() const { return (_s == 0); }
  340. private:
  341. template<typename O>
  342. static inline unsigned long _hc(const O &obj)
  343. {
  344. return (unsigned long)obj.hashCode();
  345. }
  346. static inline unsigned long _hc(const uint64_t i)
  347. {
  348. return (unsigned long)(i ^ (i >> 32)); // good for network IDs and addresses
  349. }
  350. static inline unsigned long _hc(const uint32_t i)
  351. {
  352. return ((unsigned long)i * (unsigned long)0x9e3779b1);
  353. }
  354. static inline unsigned long _hc(const uint16_t i)
  355. {
  356. return ((unsigned long)i * (unsigned long)0x9e3779b1);
  357. }
  358. inline void _grow()
  359. {
  360. const unsigned long nc = _bc * 2;
  361. _Bucket **nt = reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * nc));
  362. if (nt) {
  363. for(unsigned long i=0;i<nc;++i)
  364. nt[i] = (_Bucket *)0;
  365. for(unsigned long i=0;i<_bc;++i) {
  366. _Bucket *b = _t[i];
  367. while (b) {
  368. _Bucket *const nb = b->next;
  369. const unsigned long nidx = _hc(b->k) % nc;
  370. b->next = nt[nidx];
  371. nt[nidx] = b;
  372. b = nb;
  373. }
  374. }
  375. ::free(_t);
  376. _t = nt;
  377. _bc = nc;
  378. }
  379. }
  380. _Bucket **_t;
  381. unsigned long _bc;
  382. unsigned long _s;
  383. };
  384. } // namespace ZeroTier
  385. #endif