juce_HashMap.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. #ifndef JUCE_HASHMAP_H_INCLUDED
  22. #define JUCE_HASHMAP_H_INCLUDED
  23. //==============================================================================
  24. /**
  25. A simple class to generate hash functions for some primitive types, intended for
  26. use with the HashMap class.
  27. @see HashMap
  28. */
  29. struct DefaultHashFunctions
  30. {
  31. /** Generates a simple hash from an integer. */
  32. int generateHash (const int key, const int upperLimit) const noexcept { return std::abs (key) % upperLimit; }
  33. /** Generates a simple hash from an int64. */
  34. int generateHash (const int64 key, const int upperLimit) const noexcept { return std::abs ((int) key) % upperLimit; }
  35. /** Generates a simple hash from a string. */
  36. int generateHash (const String& key, const int upperLimit) const noexcept { return (int) (((uint32) key.hashCode()) % (uint32) upperLimit); }
  37. /** Generates a simple hash from a variant. */
  38. int generateHash (const var& key, const int upperLimit) const noexcept { return generateHash (key.toString(), upperLimit); }
  39. /** Generates a simple hash from a void ptr. */
  40. int generateHash (const void* key, const int upperLimit) const noexcept { return (int)(((pointer_sized_uint) key) % ((pointer_sized_uint) upperLimit)); }
  41. };
  42. //==============================================================================
  43. /**
  44. Holds a set of mappings between some key/value pairs.
  45. The types of the key and value objects are set as template parameters.
  46. You can also specify a class to supply a hash function that converts a key value
  47. into an hashed integer. This class must have the form:
  48. @code
  49. struct MyHashGenerator
  50. {
  51. int generateHash (MyKeyType key, int upperLimit) const
  52. {
  53. // The function must return a value 0 <= x < upperLimit
  54. return someFunctionOfMyKeyType (key) % upperLimit;
  55. }
  56. };
  57. @endcode
  58. Like the Array class, the key and value types are expected to be copy-by-value
  59. types, so if you define them to be pointer types, this class won't delete the
  60. objects that they point to.
  61. If you don't supply a class for the HashFunctionType template parameter, the
  62. default one provides some simple mappings for strings and ints.
  63. @code
  64. HashMap<int, String> hash;
  65. hash.set (1, "item1");
  66. hash.set (2, "item2");
  67. DBG (hash [1]); // prints "item1"
  68. DBG (hash [2]); // prints "item2"
  69. // This iterates the map, printing all of its key -> value pairs..
  70. for (HashMap<int, String>::Iterator i (hash); i.next();)
  71. DBG (i.getKey() << " -> " << i.getValue());
  72. @endcode
  73. @tparam HashFunctionType The class of hash function, which must be copy-constructible.
  74. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  75. */
  76. template <typename KeyType,
  77. typename ValueType,
  78. class HashFunctionType = DefaultHashFunctions,
  79. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  80. class HashMap
  81. {
  82. private:
  83. typedef PARAMETER_TYPE (KeyType) KeyTypeParameter;
  84. typedef PARAMETER_TYPE (ValueType) ValueTypeParameter;
  85. public:
  86. //==============================================================================
  87. /** Creates an empty hash-map.
  88. @param numberOfSlots Specifies the number of hash entries the map will use. This will be
  89. the "upperLimit" parameter that is passed to your generateHash()
  90. function. The number of hash slots will grow automatically if necessary,
  91. or it can be remapped manually using remapTable().
  92. @param hashFunction An instance of HashFunctionType, which will be copied and
  93. stored to use with the HashMap. This parameter can be omitted
  94. if HashFunctionType has a default constructor.
  95. */
  96. explicit HashMap (int numberOfSlots = defaultHashTableSize,
  97. HashFunctionType hashFunction = HashFunctionType())
  98. : hashFunctionToUse (hashFunction), totalNumItems (0)
  99. {
  100. hashSlots.insertMultiple (0, nullptr, numberOfSlots);
  101. }
  102. /** Destructor. */
  103. ~HashMap()
  104. {
  105. clear();
  106. }
  107. //==============================================================================
  108. /** Removes all values from the map.
  109. Note that this will clear the content, but won't affect the number of slots (see
  110. remapTable and getNumSlots).
  111. */
  112. void clear()
  113. {
  114. const ScopedLockType sl (getLock());
  115. for (int i = hashSlots.size(); --i >= 0;)
  116. {
  117. HashEntry* h = hashSlots.getUnchecked(i);
  118. while (h != nullptr)
  119. {
  120. const ScopedPointer<HashEntry> deleter (h);
  121. h = h->nextEntry;
  122. }
  123. hashSlots.set (i, nullptr);
  124. }
  125. totalNumItems = 0;
  126. }
  127. //==============================================================================
  128. /** Returns the current number of items in the map. */
  129. inline int size() const noexcept
  130. {
  131. return totalNumItems;
  132. }
  133. /** Returns the value corresponding to a given key.
  134. If the map doesn't contain the key, a default instance of the value type is returned.
  135. @param keyToLookFor the key of the item being requested
  136. */
  137. inline ValueType operator[] (KeyTypeParameter keyToLookFor) const
  138. {
  139. const ScopedLockType sl (getLock());
  140. for (const HashEntry* entry = hashSlots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  141. if (entry->key == keyToLookFor)
  142. return entry->value;
  143. return ValueType();
  144. }
  145. //==============================================================================
  146. /** Returns true if the map contains an item with the specied key. */
  147. bool contains (KeyTypeParameter keyToLookFor) const
  148. {
  149. const ScopedLockType sl (getLock());
  150. for (const HashEntry* entry = hashSlots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  151. if (entry->key == keyToLookFor)
  152. return true;
  153. return false;
  154. }
  155. /** Returns true if the hash contains at least one occurrence of a given value. */
  156. bool containsValue (ValueTypeParameter valueToLookFor) const
  157. {
  158. const ScopedLockType sl (getLock());
  159. for (int i = getNumSlots(); --i >= 0;)
  160. for (const HashEntry* entry = hashSlots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  161. if (entry->value == valueToLookFor)
  162. return true;
  163. return false;
  164. }
  165. //==============================================================================
  166. /** Adds or replaces an element in the hash-map.
  167. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  168. will be added to the map.
  169. */
  170. void set (KeyTypeParameter newKey, ValueTypeParameter newValue)
  171. {
  172. const ScopedLockType sl (getLock());
  173. const int hashIndex = generateHashFor (newKey);
  174. HashEntry* const firstEntry = hashSlots.getUnchecked (hashIndex);
  175. for (HashEntry* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
  176. {
  177. if (entry->key == newKey)
  178. {
  179. entry->value = newValue;
  180. return;
  181. }
  182. }
  183. hashSlots.set (hashIndex, new HashEntry (newKey, newValue, firstEntry));
  184. ++totalNumItems;
  185. if (totalNumItems > (getNumSlots() * 3) / 2)
  186. remapTable (getNumSlots() * 2);
  187. }
  188. /** Removes an item with the given key. */
  189. void remove (KeyTypeParameter keyToRemove)
  190. {
  191. const ScopedLockType sl (getLock());
  192. const int hashIndex = generateHashFor (keyToRemove);
  193. HashEntry* entry = hashSlots.getUnchecked (hashIndex);
  194. HashEntry* previous = nullptr;
  195. while (entry != nullptr)
  196. {
  197. if (entry->key == keyToRemove)
  198. {
  199. const ScopedPointer<HashEntry> deleter (entry);
  200. entry = entry->nextEntry;
  201. if (previous != nullptr)
  202. previous->nextEntry = entry;
  203. else
  204. hashSlots.set (hashIndex, entry);
  205. --totalNumItems;
  206. }
  207. else
  208. {
  209. previous = entry;
  210. entry = entry->nextEntry;
  211. }
  212. }
  213. }
  214. /** Removes all items with the given value. */
  215. void removeValue (ValueTypeParameter valueToRemove)
  216. {
  217. const ScopedLockType sl (getLock());
  218. for (int i = getNumSlots(); --i >= 0;)
  219. {
  220. HashEntry* entry = hashSlots.getUnchecked(i);
  221. HashEntry* previous = nullptr;
  222. while (entry != nullptr)
  223. {
  224. if (entry->value == valueToRemove)
  225. {
  226. const ScopedPointer<HashEntry> deleter (entry);
  227. entry = entry->nextEntry;
  228. if (previous != nullptr)
  229. previous->nextEntry = entry;
  230. else
  231. hashSlots.set (i, entry);
  232. --totalNumItems;
  233. }
  234. else
  235. {
  236. previous = entry;
  237. entry = entry->nextEntry;
  238. }
  239. }
  240. }
  241. }
  242. /** Remaps the hash-map to use a different number of slots for its hash function.
  243. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  244. @see getNumSlots()
  245. */
  246. void remapTable (int newNumberOfSlots)
  247. {
  248. HashMap newTable (newNumberOfSlots);
  249. for (int i = getNumSlots(); --i >= 0;)
  250. for (const HashEntry* entry = hashSlots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  251. newTable.set (entry->key, entry->value);
  252. swapWith (newTable);
  253. }
  254. /** Returns the number of slots which are available for hashing.
  255. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  256. @see getNumSlots()
  257. */
  258. inline int getNumSlots() const noexcept
  259. {
  260. return hashSlots.size();
  261. }
  262. //==============================================================================
  263. /** Efficiently swaps the contents of two hash-maps. */
  264. template <class OtherHashMapType>
  265. void swapWith (OtherHashMapType& otherHashMap) noexcept
  266. {
  267. const ScopedLockType lock1 (getLock());
  268. const typename OtherHashMapType::ScopedLockType lock2 (otherHashMap.getLock());
  269. hashSlots.swapWith (otherHashMap.hashSlots);
  270. std::swap (totalNumItems, otherHashMap.totalNumItems);
  271. }
  272. //==============================================================================
  273. /** Returns the CriticalSection that locks this structure.
  274. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  275. an object of ScopedLockType as an RAII lock for it.
  276. */
  277. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; }
  278. /** Returns the type of scoped lock to use for locking this array */
  279. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  280. private:
  281. //==============================================================================
  282. class HashEntry
  283. {
  284. public:
  285. HashEntry (KeyTypeParameter k, ValueTypeParameter val, HashEntry* const next)
  286. : key (k), value (val), nextEntry (next)
  287. {}
  288. const KeyType key;
  289. ValueType value;
  290. HashEntry* nextEntry;
  291. JUCE_DECLARE_NON_COPYABLE (HashEntry)
  292. };
  293. public:
  294. //==============================================================================
  295. /** Iterates over the items in a HashMap.
  296. To use it, repeatedly call next() until it returns false, e.g.
  297. @code
  298. HashMap <String, String> myMap;
  299. HashMap<String, String>::Iterator i (myMap);
  300. while (i.next())
  301. {
  302. DBG (i.getKey() << " -> " << i.getValue());
  303. }
  304. @endcode
  305. The order in which items are iterated bears no resemblence to the order in which
  306. they were originally added!
  307. Obviously as soon as you call any non-const methods on the original hash-map, any
  308. iterators that were created beforehand will cease to be valid, and should not be used.
  309. @see HashMap
  310. */
  311. class Iterator
  312. {
  313. public:
  314. //==============================================================================
  315. Iterator (const HashMap& hashMapToIterate)
  316. : hashMap (hashMapToIterate), entry (nullptr), index (0)
  317. {}
  318. /** Moves to the next item, if one is available.
  319. When this returns true, you can get the item's key and value using getKey() and
  320. getValue(). If it returns false, the iteration has finished and you should stop.
  321. */
  322. bool next()
  323. {
  324. if (entry != nullptr)
  325. entry = entry->nextEntry;
  326. while (entry == nullptr)
  327. {
  328. if (index >= hashMap.getNumSlots())
  329. return false;
  330. entry = hashMap.hashSlots.getUnchecked (index++);
  331. }
  332. return true;
  333. }
  334. /** Returns the current item's key.
  335. This should only be called when a call to next() has just returned true.
  336. */
  337. KeyType getKey() const
  338. {
  339. return entry != nullptr ? entry->key : KeyType();
  340. }
  341. /** Returns the current item's value.
  342. This should only be called when a call to next() has just returned true.
  343. */
  344. ValueType getValue() const
  345. {
  346. return entry != nullptr ? entry->value : ValueType();
  347. }
  348. /** Resets the iterator to its starting position. */
  349. void reset() noexcept
  350. {
  351. entry = nullptr;
  352. index = 0;
  353. }
  354. private:
  355. //==============================================================================
  356. const HashMap& hashMap;
  357. HashEntry* entry;
  358. int index;
  359. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Iterator)
  360. };
  361. private:
  362. //==============================================================================
  363. enum { defaultHashTableSize = 101 };
  364. friend class Iterator;
  365. HashFunctionType hashFunctionToUse;
  366. Array<HashEntry*> hashSlots;
  367. int totalNumItems;
  368. TypeOfCriticalSectionToUse lock;
  369. int generateHashFor (KeyTypeParameter key) const
  370. {
  371. const int hash = hashFunctionToUse.generateHash (key, getNumSlots());
  372. jassert (isPositiveAndBelow (hash, getNumSlots())); // your hash function is generating out-of-range numbers!
  373. return hash;
  374. }
  375. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap)
  376. };
  377. #endif // JUCE_HASHMAP_H_INCLUDED