HashMap.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #ifndef CORE_HASHMAP_H
  2. #define CORE_HASHMAP_H
  3. #include "data/LinkedList.h"
  4. #include "data/List.h"
  5. #include "utils/ArrayString.h"
  6. namespace Core {
  7. template<typename K, typename V>
  8. struct HashMap final {
  9. class Node final {
  10. friend HashMap;
  11. friend List<Node>;
  12. friend LinkedList<Node>;
  13. K key;
  14. public:
  15. V value;
  16. const K& getKey() const {
  17. return key;
  18. }
  19. private:
  20. template<typename... Args>
  21. Node(const K& key_, Args&&... args)
  22. : key(key_), value(Core::forward<Args>(args)...) {
  23. }
  24. };
  25. using NodePointer = LinkedList<Node>::Node*;
  26. using NodePointerList = List<NodePointer>;
  27. using NodeIterator = LinkedList<Node>::Iterator;
  28. using ConstNodeIterator = LinkedList<Node>::ConstIterator;
  29. template<typename N, typename I, typename R, R& (*A)(I&)>
  30. class Iterator final {
  31. N iterator;
  32. public:
  33. Iterator(N iterator_) : iterator(iterator_) {
  34. }
  35. Iterator& operator++() {
  36. ++iterator;
  37. return *this;
  38. }
  39. bool operator!=(const Iterator& other) const {
  40. return iterator != other.iterator;
  41. }
  42. R& operator*() const {
  43. return A(*iterator);
  44. }
  45. };
  46. template<typename R>
  47. static R& access(R& node) {
  48. return node;
  49. }
  50. template<typename I, typename R>
  51. static R& accessValue(I& node) {
  52. return node.value;
  53. }
  54. static const K& accessKey(const Node& node) {
  55. return node.getKey();
  56. }
  57. template<typename N, typename R>
  58. using BaseEntryIterator = Iterator<N, R, R, access<R>>;
  59. using EntryIterator = BaseEntryIterator<NodeIterator, Node>;
  60. using ConstEntryIterator =
  61. BaseEntryIterator<ConstNodeIterator, const Node>;
  62. template<typename N, typename I, typename R>
  63. using BaseValueIterator = Iterator<N, I, R, accessValue<I, R>>;
  64. using ValueIterator = BaseValueIterator<NodeIterator, Node, V>;
  65. using ConstValueIterator =
  66. BaseValueIterator<ConstNodeIterator, const Node, const V>;
  67. using ConstKeyIterator =
  68. Iterator<ConstNodeIterator, const Node, const K, accessKey>;
  69. template<typename M, typename I>
  70. struct IteratorAdapter final {
  71. M& map;
  72. I begin() const {
  73. return I(map.nodes.begin());
  74. }
  75. I end() const {
  76. return I(map.nodes.end());
  77. }
  78. };
  79. using EntryIteratorAdapter = IteratorAdapter<HashMap, EntryIterator>;
  80. using ConstEntryIteratorAdapter =
  81. IteratorAdapter<const HashMap, ConstEntryIterator>;
  82. using ValueIteratorAdapter = IteratorAdapter<HashMap, ValueIterator>;
  83. using ConstValueIteratorAdapter =
  84. IteratorAdapter<const HashMap, ConstValueIterator>;
  85. using ConstKeyIteratorAdapter =
  86. IteratorAdapter<const HashMap, ConstKeyIterator>;
  87. private:
  88. LinkedList<Node> nodes;
  89. List<NodePointerList> nodePointers;
  90. public:
  91. // returns true on error
  92. check_return bool copyFrom(const HashMap& other) {
  93. HashMap copy;
  94. for(const auto& e : other) {
  95. if(copy.add(e.getKey(), e.value)) {
  96. return true;
  97. }
  98. }
  99. swap(copy.nodes, nodes);
  100. swap(copy.nodePointers, nodePointers);
  101. return false;
  102. }
  103. // returns true on error
  104. check_return bool rehash(int minCapacity) {
  105. if(minCapacity <= nodePointers.getLength()) {
  106. return false;
  107. }
  108. HashMap<K, V> map;
  109. int l = 1 << Math::roundUpLog2(Core::Math::max(minCapacity, 8));
  110. if(map.nodePointers.resize(l)) {
  111. return true;
  112. }
  113. for(NodePointerList& list : nodePointers) {
  114. for(NodePointer& n : list) {
  115. int h = map.hashIndex(n->data.key);
  116. if(map.nodePointers[h].add(n)) {
  117. return true;
  118. }
  119. }
  120. }
  121. Core::swap(map.nodePointers, nodePointers);
  122. return false;
  123. }
  124. // returns true on error
  125. template<typename... Args>
  126. check_return bool tryEmplace(const K& key, Args&&... args) {
  127. if(rehash(nodes.getLength() + 1)) {
  128. return true;
  129. }
  130. int h = hashIndex(key);
  131. V* v = searchList(key, h);
  132. if(v != nullptr) {
  133. return true;
  134. }
  135. NodePointer np = nodes.add(key, Core::forward<Args>(args)...);
  136. if(np == nullptr) {
  137. return true;
  138. } else if(nodePointers[h].add(np)) {
  139. nodes.remove(np);
  140. return true;
  141. }
  142. return false;
  143. }
  144. // returns true on error
  145. template<typename VA>
  146. check_return bool add(const K& key, VA&& value) {
  147. if(rehash(nodes.getLength() + 1)) {
  148. return true;
  149. }
  150. int h = hashIndex(key);
  151. V* v = searchList(key, h);
  152. if(v == nullptr) {
  153. NodePointer np = nodes.add(key, Core::forward<VA>(value));
  154. if(np == nullptr) {
  155. return true;
  156. } else if(nodePointers[h].add(np)) {
  157. nodes.remove(np);
  158. return true;
  159. }
  160. } else {
  161. *v = Core::forward<VA>(value);
  162. }
  163. return false;
  164. }
  165. // returns true when a value was removed
  166. check_return bool remove(const K& key) {
  167. NodePointerList& list = nodePointers[hashIndex(key)];
  168. for(int i = 0; i < list.getLength(); i++) {
  169. if(list[i]->data.key == key) {
  170. NodePointer np = list[i];
  171. bool r = list.removeBySwap(i);
  172. nodes.remove(np);
  173. return !r;
  174. }
  175. }
  176. return false;
  177. }
  178. const V* search(const K& key) const {
  179. return searchList(key, hashIndex(key));
  180. }
  181. V* search(const K& key) {
  182. return searchList(key, hashIndex(key));
  183. }
  184. bool contains(const K& key) const {
  185. return search(key) != nullptr;
  186. }
  187. HashMap& clear() {
  188. nodes.clear();
  189. for(NodePointerList& n : nodePointers) {
  190. n.clear();
  191. }
  192. return *this;
  193. }
  194. EntryIteratorAdapter entries() {
  195. return {*this};
  196. }
  197. ConstEntryIteratorAdapter entries() const {
  198. return {*this};
  199. }
  200. ConstKeyIteratorAdapter keys() const {
  201. return {*this};
  202. }
  203. ValueIteratorAdapter values() {
  204. return {*this};
  205. }
  206. ConstValueIteratorAdapter values() const {
  207. return {*this};
  208. }
  209. EntryIterator begin() {
  210. return EntryIterator(nodes.begin());
  211. }
  212. EntryIterator end() {
  213. return EntryIterator(nodes.end());
  214. }
  215. ConstEntryIterator begin() const {
  216. return ConstEntryIterator(nodes.begin());
  217. }
  218. ConstEntryIterator end() const {
  219. return ConstEntryIterator(nodes.end());
  220. }
  221. // returns true on error
  222. template<int L>
  223. check_return bool toString(ArrayString<L>& s) const {
  224. if(s.append("[")) {
  225. return true;
  226. }
  227. bool c = false;
  228. for(const NodePointerList& list : nodePointers) {
  229. for(const NodePointer& n : list) {
  230. if(c && s.append(", ")) {
  231. return true;
  232. } else if(s.append(n->data.key) || s.append(" = ") ||
  233. s.append(n->data.value)) {
  234. return true;
  235. }
  236. c = true;
  237. }
  238. }
  239. return s.append("]");
  240. }
  241. private:
  242. template<typename H>
  243. int hashIndex(const H& key) const {
  244. return static_cast<int>(fullHash(key)) &
  245. (nodePointers.getLength() - 1);
  246. }
  247. template<typename H>
  248. Hash fullHash(const H& key) const {
  249. return key.hashCode();
  250. }
  251. Hash fullHash(int key) const {
  252. static_assert(sizeof(key) == sizeof(Hash),
  253. "unwanted loose of precision in hash");
  254. return static_cast<Hash>(key);
  255. }
  256. Hash fullHash(unsigned int key) const {
  257. static_assert(sizeof(key) == sizeof(Hash),
  258. "unwanted loose of precision in hash");
  259. return key;
  260. }
  261. const V* searchList(const K& key, int h) const {
  262. if(nodePointers.getLength() == 0) {
  263. return nullptr;
  264. }
  265. for(const NodePointer& n : nodePointers[h]) {
  266. if(n->data.key == key) {
  267. return &n->data.value;
  268. }
  269. }
  270. return nullptr;
  271. }
  272. V* searchList(const K& key, int h) {
  273. return const_cast<V*>(
  274. static_cast<const HashMap*>(this)->searchList(key, h));
  275. }
  276. };
  277. }
  278. #endif