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.

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