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.

448 lines
15KB

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