The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

461 lines
16KB

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