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.

483 lines
17KB

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