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.

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