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.

471 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. #pragma once
  18. //==============================================================================
  19. /**
  20. A simple class to generate hash functions for some primitive types, intended for
  21. use with the HashMap class.
  22. @see HashMap
  23. */
  24. struct DefaultHashFunctions
  25. {
  26. /** Generates a simple hash from an integer. */
  27. int generateHash (const int key, const int upperLimit) const noexcept { return std::abs (key) % upperLimit; }
  28. /** Generates a simple hash from an int64. */
  29. int generateHash (const int64 key, const int upperLimit) const noexcept { return std::abs ((int) key) % upperLimit; }
  30. /** Generates a simple hash from a string. */
  31. int generateHash (const String& key, const int upperLimit) const noexcept { return (int) (((uint32) key.hashCode()) % (uint32) upperLimit); }
  32. /** Generates a simple hash from a variant. */
  33. int generateHash (const var& key, const int upperLimit) const noexcept { return generateHash (key.toString(), upperLimit); }
  34. /** Generates a simple hash from a void ptr. */
  35. int generateHash (const void* key, const int upperLimit) const noexcept { return (int)(((pointer_sized_uint) key) % ((pointer_sized_uint) upperLimit)); }
  36. };
  37. //==============================================================================
  38. /**
  39. Holds a set of mappings between some key/value pairs.
  40. The types of the key and value objects are set as template parameters.
  41. You can also specify a class to supply a hash function that converts a key value
  42. into an hashed integer. This class must have the form:
  43. @code
  44. struct MyHashGenerator
  45. {
  46. int generateHash (MyKeyType key, int upperLimit) const
  47. {
  48. // The function must return a value 0 <= x < upperLimit
  49. return someFunctionOfMyKeyType (key) % upperLimit;
  50. }
  51. };
  52. @endcode
  53. Like the Array class, the key and value types are expected to be copy-by-value
  54. types, so if you define them to be pointer types, this class won't delete the
  55. objects that they point to.
  56. If you don't supply a class for the HashFunctionType template parameter, the
  57. default one provides some simple mappings for strings and ints.
  58. @code
  59. HashMap<int, String> hash;
  60. hash.set (1, "item1");
  61. hash.set (2, "item2");
  62. DBG (hash [1]); // prints "item1"
  63. DBG (hash [2]); // prints "item2"
  64. // This iterates the map, printing all of its key -> value pairs..
  65. for (HashMap<int, String>::Iterator i (hash); i.next();)
  66. DBG (i.getKey() << " -> " << i.getValue());
  67. @endcode
  68. @tparam HashFunctionType The class of hash function, which must be copy-constructible.
  69. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  70. */
  71. template <typename KeyType,
  72. typename ValueType,
  73. class HashFunctionType = DefaultHashFunctions,
  74. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  75. class HashMap
  76. {
  77. private:
  78. typedef typename TypeHelpers::ParameterType<KeyType>::type KeyTypeParameter;
  79. typedef typename TypeHelpers::ParameterType<ValueType>::type ValueTypeParameter;
  80. public:
  81. //==============================================================================
  82. /** Creates an empty hash-map.
  83. @param numberOfSlots Specifies the number of hash entries the map will use. This will be
  84. the "upperLimit" parameter that is passed to your generateHash()
  85. function. The number of hash slots will grow automatically if necessary,
  86. or it can be remapped manually using remapTable().
  87. @param hashFunction An instance of HashFunctionType, which will be copied and
  88. stored to use with the HashMap. This parameter can be omitted
  89. if HashFunctionType has a default constructor.
  90. */
  91. explicit HashMap (int numberOfSlots = defaultHashTableSize,
  92. HashFunctionType hashFunction = HashFunctionType())
  93. : hashFunctionToUse (hashFunction), totalNumItems (0)
  94. {
  95. hashSlots.insertMultiple (0, nullptr, numberOfSlots);
  96. }
  97. /** Destructor. */
  98. ~HashMap()
  99. {
  100. clear();
  101. }
  102. //==============================================================================
  103. /** Removes all values from the map.
  104. Note that this will clear the content, but won't affect the number of slots (see
  105. remapTable and getNumSlots).
  106. */
  107. void clear()
  108. {
  109. const ScopedLockType sl (getLock());
  110. for (int i = hashSlots.size(); --i >= 0;)
  111. {
  112. HashEntry* h = hashSlots.getUnchecked(i);
  113. while (h != nullptr)
  114. {
  115. const ScopedPointer<HashEntry> deleter (h);
  116. h = h->nextEntry;
  117. }
  118. hashSlots.set (i, nullptr);
  119. }
  120. totalNumItems = 0;
  121. }
  122. //==============================================================================
  123. /** Returns the current number of items in the map. */
  124. inline int size() const noexcept
  125. {
  126. return totalNumItems;
  127. }
  128. /** Returns the value corresponding to a given key.
  129. If the map doesn't contain the key, a default instance of the value type is returned.
  130. @param keyToLookFor the key of the item being requested
  131. */
  132. inline ValueType operator[] (KeyTypeParameter keyToLookFor) const
  133. {
  134. const ScopedLockType sl (getLock());
  135. for (const HashEntry* entry = hashSlots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  136. if (entry->key == keyToLookFor)
  137. return entry->value;
  138. return ValueType();
  139. }
  140. //==============================================================================
  141. /** Returns true if the map contains an item with the specied key. */
  142. bool contains (KeyTypeParameter keyToLookFor) const
  143. {
  144. const ScopedLockType sl (getLock());
  145. for (const HashEntry* entry = hashSlots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  146. if (entry->key == keyToLookFor)
  147. return true;
  148. return false;
  149. }
  150. /** Returns true if the hash contains at least one occurrence of a given value. */
  151. bool containsValue (ValueTypeParameter valueToLookFor) const
  152. {
  153. const ScopedLockType sl (getLock());
  154. for (int i = getNumSlots(); --i >= 0;)
  155. for (const HashEntry* entry = hashSlots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  156. if (entry->value == valueToLookFor)
  157. return true;
  158. return false;
  159. }
  160. //==============================================================================
  161. /** Adds or replaces an element in the hash-map.
  162. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  163. will be added to the map.
  164. */
  165. void set (KeyTypeParameter newKey, ValueTypeParameter newValue)
  166. {
  167. const ScopedLockType sl (getLock());
  168. const int hashIndex = generateHashFor (newKey);
  169. HashEntry* const firstEntry = hashSlots.getUnchecked (hashIndex);
  170. for (HashEntry* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
  171. {
  172. if (entry->key == newKey)
  173. {
  174. entry->value = newValue;
  175. return;
  176. }
  177. }
  178. hashSlots.set (hashIndex, new HashEntry (newKey, newValue, firstEntry));
  179. ++totalNumItems;
  180. if (totalNumItems > (getNumSlots() * 3) / 2)
  181. remapTable (getNumSlots() * 2);
  182. }
  183. /** Removes an item with the given key. */
  184. void remove (KeyTypeParameter keyToRemove)
  185. {
  186. const ScopedLockType sl (getLock());
  187. const int hashIndex = generateHashFor (keyToRemove);
  188. HashEntry* entry = hashSlots.getUnchecked (hashIndex);
  189. HashEntry* previous = nullptr;
  190. while (entry != nullptr)
  191. {
  192. if (entry->key == keyToRemove)
  193. {
  194. const ScopedPointer<HashEntry> deleter (entry);
  195. entry = entry->nextEntry;
  196. if (previous != nullptr)
  197. previous->nextEntry = entry;
  198. else
  199. hashSlots.set (hashIndex, entry);
  200. --totalNumItems;
  201. }
  202. else
  203. {
  204. previous = entry;
  205. entry = entry->nextEntry;
  206. }
  207. }
  208. }
  209. /** Removes all items with the given value. */
  210. void removeValue (ValueTypeParameter valueToRemove)
  211. {
  212. const ScopedLockType sl (getLock());
  213. for (int i = getNumSlots(); --i >= 0;)
  214. {
  215. HashEntry* entry = hashSlots.getUnchecked(i);
  216. HashEntry* previous = nullptr;
  217. while (entry != nullptr)
  218. {
  219. if (entry->value == valueToRemove)
  220. {
  221. const ScopedPointer<HashEntry> deleter (entry);
  222. entry = entry->nextEntry;
  223. if (previous != nullptr)
  224. previous->nextEntry = entry;
  225. else
  226. hashSlots.set (i, entry);
  227. --totalNumItems;
  228. }
  229. else
  230. {
  231. previous = entry;
  232. entry = entry->nextEntry;
  233. }
  234. }
  235. }
  236. }
  237. /** Remaps the hash-map to use a different number of slots for its hash function.
  238. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  239. @see getNumSlots()
  240. */
  241. void remapTable (int newNumberOfSlots)
  242. {
  243. HashMap newTable (newNumberOfSlots);
  244. for (int i = getNumSlots(); --i >= 0;)
  245. for (const HashEntry* entry = hashSlots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  246. newTable.set (entry->key, entry->value);
  247. swapWith (newTable);
  248. }
  249. /** Returns the number of slots which are available for hashing.
  250. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  251. @see getNumSlots()
  252. */
  253. inline int getNumSlots() const noexcept
  254. {
  255. return hashSlots.size();
  256. }
  257. //==============================================================================
  258. /** Efficiently swaps the contents of two hash-maps. */
  259. template <class OtherHashMapType>
  260. void swapWith (OtherHashMapType& otherHashMap) noexcept
  261. {
  262. const ScopedLockType lock1 (getLock());
  263. const typename OtherHashMapType::ScopedLockType lock2 (otherHashMap.getLock());
  264. hashSlots.swapWith (otherHashMap.hashSlots);
  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. struct Iterator
  307. {
  308. Iterator (const HashMap& hashMapToIterate) noexcept
  309. : hashMap (hashMapToIterate), entry (nullptr), index (0)
  310. {}
  311. Iterator (const Iterator& other) noexcept
  312. : hashMap (other.hashMap), entry (other.entry), index (other.index)
  313. {}
  314. /** Moves to the next item, if one is available.
  315. When this returns true, you can get the item's key and value using getKey() and
  316. getValue(). If it returns false, the iteration has finished and you should stop.
  317. */
  318. bool next() noexcept
  319. {
  320. if (entry != nullptr)
  321. entry = entry->nextEntry;
  322. while (entry == nullptr)
  323. {
  324. if (index >= hashMap.getNumSlots())
  325. return false;
  326. entry = hashMap.hashSlots.getUnchecked (index++);
  327. }
  328. return true;
  329. }
  330. /** Returns the current item's key.
  331. This should only be called when a call to next() has just returned true.
  332. */
  333. KeyType getKey() const
  334. {
  335. return entry != nullptr ? entry->key : KeyType();
  336. }
  337. /** Returns the current item's value.
  338. This should only be called when a call to next() has just returned true.
  339. */
  340. ValueType getValue() const
  341. {
  342. return entry != nullptr ? entry->value : ValueType();
  343. }
  344. /** Resets the iterator to its starting position. */
  345. void reset() noexcept
  346. {
  347. entry = nullptr;
  348. index = 0;
  349. }
  350. Iterator& operator++() noexcept { next(); return *this; }
  351. ValueType operator*() const { return getValue(); }
  352. bool operator!= (const Iterator& other) const noexcept { return entry != other.entry || index != other.index; }
  353. void resetToEnd() noexcept { index = hashMap.getNumSlots(); }
  354. private:
  355. //==============================================================================
  356. const HashMap& hashMap;
  357. HashEntry* entry;
  358. int index;
  359. // using the copy constructor is ok, but you cannot assign iterators
  360. Iterator& operator= (const Iterator&) JUCE_DELETED_FUNCTION;
  361. JUCE_LEAK_DETECTOR (Iterator)
  362. };
  363. /** Returns a start iterator for the values in this tree. */
  364. Iterator begin() const noexcept { Iterator i (*this); i.next(); return i; }
  365. /** Returns an end iterator for the values in this tree. */
  366. Iterator end() const noexcept { Iterator i (*this); i.resetToEnd(); return i; }
  367. private:
  368. //==============================================================================
  369. enum { defaultHashTableSize = 101 };
  370. friend struct Iterator;
  371. HashFunctionType hashFunctionToUse;
  372. Array<HashEntry*> hashSlots;
  373. int totalNumItems;
  374. TypeOfCriticalSectionToUse lock;
  375. int generateHashFor (KeyTypeParameter key) const
  376. {
  377. const int hash = hashFunctionToUse.generateHash (key, getNumSlots());
  378. jassert (isPositiveAndBelow (hash, getNumSlots())); // your hash function is generating out-of-range numbers!
  379. return hash;
  380. }
  381. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap)
  382. };