Hashtable.hpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 <stdint.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <stdexcept>
  32. #include <vector>
  33. #include <utility>
  34. #include <algorithm>
  35. namespace ZeroTier {
  36. /**
  37. * A minimal hash table implementation for the ZeroTier core
  38. *
  39. * This is not a drop-in replacement for STL containers, and has several
  40. * limitations. Keys can be uint64_t or an object, and if the latter they
  41. * must implement a method called hashCode() that returns an unsigned long
  42. * value that is evenly distributed.
  43. */
  44. template<typename K,typename V>
  45. class Hashtable
  46. {
  47. private:
  48. struct _Bucket
  49. {
  50. _Bucket(const K &k,const V &v) : k(k),v(v) {}
  51. _Bucket(const K &k) : k(k),v() {}
  52. _Bucket(const _Bucket &b) : k(b.k),v(b.v) {}
  53. inline _Bucket &operator=(const _Bucket &b) { k = b.k; v = b.v; return *this; }
  54. K k;
  55. V v;
  56. _Bucket *next; // must be set manually for each _Bucket
  57. };
  58. public:
  59. /**
  60. * A simple forward iterator (different from STL)
  61. *
  62. * It's safe to erase the last key, but not others. Don't use set() since that
  63. * may rehash and invalidate the iterator. Note the erasing the key will destroy
  64. * the targets of the pointers returned by next().
  65. */
  66. class Iterator
  67. {
  68. public:
  69. /**
  70. * @param ht Hash table to iterate over
  71. */
  72. Iterator(Hashtable &ht) :
  73. _idx(0),
  74. _ht(&ht),
  75. _b(ht._t[0])
  76. {
  77. }
  78. /**
  79. * @param kptr Pointer to set to point to next key
  80. * @param vptr Pointer to set to point to next value
  81. * @return True if kptr and vptr are set, false if no more entries
  82. */
  83. inline bool next(K *&kptr,V *&vptr)
  84. {
  85. for(;;) {
  86. if (_b) {
  87. kptr = &(_b->k);
  88. vptr = &(_b->v);
  89. _b = _b->next;
  90. return true;
  91. }
  92. ++_idx;
  93. if (_idx >= _ht->_bc)
  94. return false;
  95. _b = _ht->_t[_idx];
  96. }
  97. }
  98. private:
  99. unsigned long _idx;
  100. Hashtable *_ht;
  101. _Bucket *_b;
  102. };
  103. friend class Hashtable::Iterator;
  104. /**
  105. * @param bc Initial capacity in buckets (default: 64, must be nonzero)
  106. */
  107. Hashtable(unsigned long bc = 64) :
  108. _t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * bc))),
  109. _bc(bc),
  110. _s(0)
  111. {
  112. if (!_t)
  113. throw ZT_EXCEPTION_OUT_OF_MEMORY;
  114. for(unsigned long i=0;i<bc;++i)
  115. _t[i] = (_Bucket *)0;
  116. }
  117. Hashtable(const Hashtable<K,V> &ht) :
  118. _t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * ht._bc))),
  119. _bc(ht._bc),
  120. _s(ht._s)
  121. {
  122. if (!_t)
  123. throw ZT_EXCEPTION_OUT_OF_MEMORY;
  124. for(unsigned long i=0;i<_bc;++i)
  125. _t[i] = (_Bucket *)0;
  126. for(unsigned long i=0;i<_bc;++i) {
  127. const _Bucket *b = ht._t[i];
  128. while (b) {
  129. _Bucket *nb = new _Bucket(*b);
  130. nb->next = _t[i];
  131. _t[i] = nb;
  132. b = b->next;
  133. }
  134. }
  135. }
  136. ~Hashtable()
  137. {
  138. this->clear();
  139. ::free(_t);
  140. }
  141. inline Hashtable &operator=(const Hashtable<K,V> &ht)
  142. {
  143. this->clear();
  144. if (ht._s) {
  145. for(unsigned long i=0;i<ht._bc;++i) {
  146. const _Bucket *b = ht._t[i];
  147. while (b) {
  148. this->set(b->k,b->v);
  149. b = b->next;
  150. }
  151. }
  152. }
  153. return *this;
  154. }
  155. /**
  156. * Erase all entries
  157. */
  158. inline void clear()
  159. {
  160. if (_s) {
  161. for(unsigned long i=0;i<_bc;++i) {
  162. _Bucket *b = _t[i];
  163. while (b) {
  164. _Bucket *const nb = b->next;
  165. delete b;
  166. b = nb;
  167. }
  168. _t[i] = (_Bucket *)0;
  169. }
  170. _s = 0;
  171. }
  172. }
  173. /**
  174. * @return Vector of all keys
  175. */
  176. inline typename std::vector<K> keys() const
  177. {
  178. typename std::vector<K> k;
  179. if (_s) {
  180. k.reserve(_s);
  181. for(unsigned long i=0;i<_bc;++i) {
  182. _Bucket *b = _t[i];
  183. while (b) {
  184. k.push_back(b->k);
  185. b = b->next;
  186. }
  187. }
  188. }
  189. return k;
  190. }
  191. /**
  192. * Append all keys (in unspecified order) to the supplied vector or list
  193. *
  194. * @param v Vector, list, or other compliant container
  195. * @tparam Type of V (generally inferred)
  196. */
  197. template<typename C>
  198. inline void appendKeys(C &v) const
  199. {
  200. if (_s) {
  201. for(unsigned long i=0;i<_bc;++i) {
  202. _Bucket *b = _t[i];
  203. while (b) {
  204. v.push_back(b->k);
  205. b = b->next;
  206. }
  207. }
  208. }
  209. }
  210. /**
  211. * @return Vector of all entries (pairs of K,V)
  212. */
  213. inline typename std::vector< std::pair<K,V> > entries() const
  214. {
  215. typename std::vector< std::pair<K,V> > k;
  216. if (_s) {
  217. k.reserve(_s);
  218. for(unsigned long i=0;i<_bc;++i) {
  219. _Bucket *b = _t[i];
  220. while (b) {
  221. k.push_back(std::pair<K,V>(b->k,b->v));
  222. b = b->next;
  223. }
  224. }
  225. }
  226. return k;
  227. }
  228. /**
  229. * @param k Key
  230. * @return Pointer to value or NULL if not found
  231. */
  232. inline V *get(const K &k)
  233. {
  234. _Bucket *b = _t[_hc(k) % _bc];
  235. while (b) {
  236. if (b->k == k)
  237. return &(b->v);
  238. b = b->next;
  239. }
  240. return (V *)0;
  241. }
  242. inline const V *get(const K &k) const { return const_cast<Hashtable *>(this)->get(k); }
  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. inline void _grow()
  358. {
  359. const unsigned long nc = _bc * 2;
  360. _Bucket **nt = reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * nc));
  361. if (nt) {
  362. for(unsigned long i=0;i<nc;++i)
  363. nt[i] = (_Bucket *)0;
  364. for(unsigned long i=0;i<_bc;++i) {
  365. _Bucket *b = _t[i];
  366. while (b) {
  367. _Bucket *const nb = b->next;
  368. const unsigned long nidx = _hc(b->k) % nc;
  369. b->next = nt[nidx];
  370. nt[nidx] = b;
  371. b = nb;
  372. }
  373. }
  374. ::free(_t);
  375. _t = nt;
  376. _bc = nc;
  377. }
  378. }
  379. _Bucket **_t;
  380. unsigned long _bc;
  381. unsigned long _s;
  382. };
  383. } // namespace ZeroTier
  384. #endif