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.

501 lines
18KB

  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. namespace juce
  18. {
  19. //==============================================================================
  20. /**
  21. A simple class to generate hash functions for some primitive types, intended for
  22. use with the HashMap class.
  23. @see HashMap
  24. */
  25. struct DefaultHashFunctions
  26. {
  27. /** Generates a simple hash from an unsigned int. */
  28. static int generateHash (uint32 key, int upperLimit) noexcept { return (int) (key % (uint32) upperLimit); }
  29. /** Generates a simple hash from an integer. */
  30. static int generateHash (int32 key, int upperLimit) noexcept { return generateHash ((uint32) key, upperLimit); }
  31. /** Generates a simple hash from a uint64. */
  32. static int generateHash (uint64 key, int upperLimit) noexcept { return (int) (key % (uint64) upperLimit); }
  33. /** Generates a simple hash from an int64. */
  34. static int generateHash (int64 key, int upperLimit) noexcept { return generateHash ((uint64) key, upperLimit); }
  35. /** Generates a simple hash from a string. */
  36. static int generateHash (const String& key, int upperLimit) noexcept { return generateHash ((uint32) key.hashCode(), upperLimit); }
  37. /** Generates a simple hash from a variant. */
  38. static int generateHash (const var& key, int upperLimit) noexcept { return generateHash (key.toString(), upperLimit); }
  39. /** Generates a simple hash from a void ptr. */
  40. static int generateHash (const void* key, int upperLimit) noexcept { return generateHash ((pointer_sized_uint) key, upperLimit); }
  41. };
  42. //==============================================================================
  43. /**
  44. Holds a set of mappings between some key/value pairs.
  45. The types of the key and value objects are set as template parameters.
  46. You can also specify a class to supply a hash function that converts a key value
  47. into an hashed integer. This class must have the form:
  48. @code
  49. struct MyHashGenerator
  50. {
  51. int generateHash (MyKeyType key, int upperLimit) const
  52. {
  53. // The function must return a value 0 <= x < upperLimit
  54. return someFunctionOfMyKeyType (key) % upperLimit;
  55. }
  56. };
  57. @endcode
  58. Like the Array class, the key and value types are expected to be copy-by-value
  59. types, so if you define them to be pointer types, this class won't delete the
  60. objects that they point to.
  61. If you don't supply a class for the HashFunctionType template parameter, the
  62. default one provides some simple mappings for strings and ints.
  63. @code
  64. HashMap<int, String> hash;
  65. hash.set (1, "item1");
  66. hash.set (2, "item2");
  67. DBG (hash [1]); // prints "item1"
  68. DBG (hash [2]); // prints "item2"
  69. // This iterates the map, printing all of its key -> value pairs..
  70. for (HashMap<int, String>::Iterator i (hash); i.next();)
  71. DBG (i.getKey() << " -> " << i.getValue());
  72. @endcode
  73. @tparam HashFunctionType The class of hash function, which must be copy-constructible.
  74. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  75. */
  76. template <typename KeyType,
  77. typename ValueType,
  78. class HashFunctionType = DefaultHashFunctions,
  79. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  80. class HashMap
  81. {
  82. private:
  83. typedef typename TypeHelpers::ParameterType<KeyType>::type KeyTypeParameter;
  84. typedef typename TypeHelpers::ParameterType<ValueType>::type ValueTypeParameter;
  85. public:
  86. //==============================================================================
  87. /** Creates an empty hash-map.
  88. @param numberOfSlots Specifies the number of hash entries the map will use. This will be
  89. the "upperLimit" parameter that is passed to your generateHash()
  90. function. The number of hash slots will grow automatically if necessary,
  91. or it can be remapped manually using remapTable().
  92. @param hashFunction An instance of HashFunctionType, which will be copied and
  93. stored to use with the HashMap. This parameter can be omitted
  94. if HashFunctionType has a default constructor.
  95. */
  96. explicit HashMap (int numberOfSlots = defaultHashTableSize,
  97. HashFunctionType hashFunction = HashFunctionType())
  98. : hashFunctionToUse (hashFunction), totalNumItems (0)
  99. {
  100. hashSlots.insertMultiple (0, nullptr, numberOfSlots);
  101. }
  102. /** Destructor. */
  103. ~HashMap()
  104. {
  105. clear();
  106. }
  107. //==============================================================================
  108. /** Removes all values from the map.
  109. Note that this will clear the content, but won't affect the number of slots (see
  110. remapTable and getNumSlots).
  111. */
  112. void clear()
  113. {
  114. const ScopedLockType sl (getLock());
  115. for (auto i = hashSlots.size(); --i >= 0;)
  116. {
  117. auto* h = hashSlots.getUnchecked(i);
  118. while (h != nullptr)
  119. {
  120. const ScopedPointer<HashEntry> deleter (h);
  121. h = h->nextEntry;
  122. }
  123. hashSlots.set (i, nullptr);
  124. }
  125. totalNumItems = 0;
  126. }
  127. //==============================================================================
  128. /** Returns the current number of items in the map. */
  129. inline int size() const noexcept
  130. {
  131. return totalNumItems;
  132. }
  133. /** Returns the value corresponding to a given key.
  134. If the map doesn't contain the key, a default instance of the value type is returned.
  135. @param keyToLookFor the key of the item being requested
  136. */
  137. inline ValueType operator[] (KeyTypeParameter keyToLookFor) const
  138. {
  139. const ScopedLockType sl (getLock());
  140. if (auto* entry = getEntry (getSlot (keyToLookFor), keyToLookFor))
  141. return entry->value;
  142. return ValueType();
  143. }
  144. /** Returns a reference to the value corresponding to a given key.
  145. If the map doesn't contain the key, a default instance of the value type is
  146. added to the map and a reference to this is returned.
  147. @param keyToLookFor the key of the item being requested
  148. */
  149. inline ValueType& getReference (KeyTypeParameter keyToLookFor)
  150. {
  151. const ScopedLockType sl (getLock());
  152. auto hashIndex = generateHashFor (keyToLookFor, getNumSlots());
  153. auto* firstEntry = hashSlots.getUnchecked (hashIndex);
  154. if (auto* entry = getEntry (firstEntry, keyToLookFor))
  155. return entry->value;
  156. auto* entry = new HashEntry (keyToLookFor, ValueType(), firstEntry);
  157. hashSlots.set (hashIndex, entry);
  158. ++totalNumItems;
  159. if (totalNumItems > (getNumSlots() * 3) / 2)
  160. remapTable (getNumSlots() * 2);
  161. return entry->value;
  162. }
  163. //==============================================================================
  164. /** Returns true if the map contains an item with the specied key. */
  165. bool contains (KeyTypeParameter keyToLookFor) const
  166. {
  167. const ScopedLockType sl (getLock());
  168. return (getEntry (getSlot (keyToLookFor), keyToLookFor) != nullptr);
  169. }
  170. /** Returns true if the hash contains at least one occurrence of a given value. */
  171. bool containsValue (ValueTypeParameter valueToLookFor) const
  172. {
  173. const ScopedLockType sl (getLock());
  174. for (auto i = getNumSlots(); --i >= 0;)
  175. for (auto* entry = hashSlots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  176. if (entry->value == valueToLookFor)
  177. return true;
  178. return false;
  179. }
  180. //==============================================================================
  181. /** Adds or replaces an element in the hash-map.
  182. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  183. will be added to the map.
  184. */
  185. void set (KeyTypeParameter newKey, ValueTypeParameter newValue) { getReference (newKey) = newValue; }
  186. /** Removes an item with the given key. */
  187. void remove (KeyTypeParameter keyToRemove)
  188. {
  189. const ScopedLockType sl (getLock());
  190. auto hashIndex = generateHashFor (keyToRemove, getNumSlots());
  191. auto* 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 (auto i = getNumSlots(); --i >= 0;)
  217. {
  218. auto* 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. const ScopedLockType sl (getLock());
  247. Array<HashEntry*> newSlots;
  248. newSlots.insertMultiple (0, nullptr, newNumberOfSlots);
  249. for (auto i = getNumSlots(); --i >= 0;)
  250. {
  251. HashEntry* nextEntry = nullptr;
  252. for (auto* entry = hashSlots.getUnchecked(i); entry != nullptr; entry = nextEntry)
  253. {
  254. auto hashIndex = generateHashFor (entry->key, newNumberOfSlots);
  255. nextEntry = entry->nextEntry;
  256. entry->nextEntry = newSlots.getUnchecked (hashIndex);
  257. newSlots.set (hashIndex, entry);
  258. }
  259. }
  260. hashSlots.swapWith (newSlots);
  261. }
  262. /** Returns the number of slots which are available for hashing.
  263. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  264. @see getNumSlots()
  265. */
  266. inline int getNumSlots() const noexcept
  267. {
  268. return hashSlots.size();
  269. }
  270. //==============================================================================
  271. /** Efficiently swaps the contents of two hash-maps. */
  272. template <class OtherHashMapType>
  273. void swapWith (OtherHashMapType& otherHashMap) noexcept
  274. {
  275. const ScopedLockType lock1 (getLock());
  276. const typename OtherHashMapType::ScopedLockType lock2 (otherHashMap.getLock());
  277. hashSlots.swapWith (otherHashMap.hashSlots);
  278. std::swap (totalNumItems, otherHashMap.totalNumItems);
  279. }
  280. //==============================================================================
  281. /** Returns the CriticalSection that locks this structure.
  282. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  283. an object of ScopedLockType as an RAII lock for it.
  284. */
  285. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; }
  286. /** Returns the type of scoped lock to use for locking this array */
  287. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  288. private:
  289. //==============================================================================
  290. class HashEntry
  291. {
  292. public:
  293. HashEntry (KeyTypeParameter k, ValueTypeParameter val, HashEntry* const next)
  294. : key (k), value (val), nextEntry (next)
  295. {}
  296. const KeyType key;
  297. ValueType value;
  298. HashEntry* nextEntry;
  299. JUCE_DECLARE_NON_COPYABLE (HashEntry)
  300. };
  301. public:
  302. //==============================================================================
  303. /** Iterates over the items in a HashMap.
  304. To use it, repeatedly call next() until it returns false, e.g.
  305. @code
  306. HashMap <String, String> myMap;
  307. HashMap<String, String>::Iterator i (myMap);
  308. while (i.next())
  309. {
  310. DBG (i.getKey() << " -> " << i.getValue());
  311. }
  312. @endcode
  313. The order in which items are iterated bears no resemblence to the order in which
  314. they were originally added!
  315. Obviously as soon as you call any non-const methods on the original hash-map, any
  316. iterators that were created beforehand will cease to be valid, and should not be used.
  317. @see HashMap
  318. */
  319. struct Iterator
  320. {
  321. Iterator (const HashMap& hashMapToIterate) noexcept
  322. : hashMap (hashMapToIterate), entry (nullptr), index (0)
  323. {}
  324. Iterator (const Iterator& other) noexcept
  325. : hashMap (other.hashMap), entry (other.entry), index (other.index)
  326. {}
  327. /** Moves to the next item, if one is available.
  328. When this returns true, you can get the item's key and value using getKey() and
  329. getValue(). If it returns false, the iteration has finished and you should stop.
  330. */
  331. bool next() noexcept
  332. {
  333. if (entry != nullptr)
  334. entry = entry->nextEntry;
  335. while (entry == nullptr)
  336. {
  337. if (index >= hashMap.getNumSlots())
  338. return false;
  339. entry = hashMap.hashSlots.getUnchecked (index++);
  340. }
  341. return true;
  342. }
  343. /** Returns the current item's key.
  344. This should only be called when a call to next() has just returned true.
  345. */
  346. KeyType getKey() const
  347. {
  348. return entry != nullptr ? entry->key : KeyType();
  349. }
  350. /** Returns the current item's value.
  351. This should only be called when a call to next() has just returned true.
  352. */
  353. ValueType getValue() const
  354. {
  355. return entry != nullptr ? entry->value : ValueType();
  356. }
  357. /** Resets the iterator to its starting position. */
  358. void reset() noexcept
  359. {
  360. entry = nullptr;
  361. index = 0;
  362. }
  363. Iterator& operator++() noexcept { next(); return *this; }
  364. ValueType operator*() const { return getValue(); }
  365. bool operator!= (const Iterator& other) const noexcept { return entry != other.entry || index != other.index; }
  366. void resetToEnd() noexcept { index = hashMap.getNumSlots(); }
  367. private:
  368. //==============================================================================
  369. const HashMap& hashMap;
  370. HashEntry* entry;
  371. int index;
  372. // using the copy constructor is ok, but you cannot assign iterators
  373. Iterator& operator= (const Iterator&) JUCE_DELETED_FUNCTION;
  374. JUCE_LEAK_DETECTOR (Iterator)
  375. };
  376. /** Returns a start iterator for the values in this tree. */
  377. Iterator begin() const noexcept { Iterator i (*this); i.next(); return i; }
  378. /** Returns an end iterator for the values in this tree. */
  379. Iterator end() const noexcept { Iterator i (*this); i.resetToEnd(); return i; }
  380. private:
  381. //==============================================================================
  382. enum { defaultHashTableSize = 101 };
  383. friend struct Iterator;
  384. HashFunctionType hashFunctionToUse;
  385. Array<HashEntry*> hashSlots;
  386. int totalNumItems;
  387. TypeOfCriticalSectionToUse lock;
  388. int generateHashFor (KeyTypeParameter key, int numSlots) const
  389. {
  390. const int hash = hashFunctionToUse.generateHash (key, numSlots);
  391. jassert (isPositiveAndBelow (hash, numSlots)); // your hash function is generating out-of-range numbers!
  392. return hash;
  393. }
  394. static inline HashEntry* getEntry (HashEntry* firstEntry, KeyType keyToLookFor) noexcept
  395. {
  396. for (auto* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
  397. if (entry->key == keyToLookFor)
  398. return entry;
  399. return nullptr;
  400. }
  401. inline HashEntry* getSlot (KeyType key) const noexcept { return hashSlots.getUnchecked (generateHashFor (key, getNumSlots())); }
  402. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap)
  403. };
  404. } // namespace juce