Dictionary.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "precompiled.h"
  29. #include "../../Include/RmlUi/Core/Dictionary.h"
  30. /* NOTE: This is dictionary implementation is copied from PYTHON
  31. which is well known for its dictionary SPEED.
  32. It uses an optimised hash table implementation. */
  33. /*
  34. There are three kinds of slots in the table:
  35. 1. Unused. me_key == me_value == NULL
  36. Does not hold an active (key, value) pair now and never did. Unused can
  37. transition to Active upon key insertion. This is the only case in which
  38. me_key is NULL, and is each slot's initial state.
  39. 2. Active. me_key != NULL and me_key != dummy and me_value != NULL
  40. Holds an active (key, value) pair. Active can transition to Dummy upon
  41. key deletion. This is the only case in which me_value != NULL.
  42. 3. Dummy. me_key == dummy and me_value == NULL
  43. Previously held an active (key, value) pair, but that was deleted and an
  44. active pair has not yet overwritten the slot. Dummy can transition to
  45. Active upon key insertion. Dummy slots cannot be made Unused again
  46. (cannot have me_key set to NULL), else the probe sequence in case of
  47. collision would have no way to know they were once active.
  48. Note: .popitem() abuses the me_hash field of an Unused or Dummy slot to
  49. hold a search finger. The me_hash field of Unused or Dummy slots has no
  50. meaning otherwise.
  51. To ensure the lookup algorithm terminates, there must be at least one Unused
  52. slot (NULL key) in the table.
  53. The value ma_fill is the number of non-NULL keys (sum of Active and Dummy);
  54. ma_used is the number of non-NULL, non-dummy keys (== the number of non-NULL
  55. values == the number of Active items).
  56. To avoid slowing down lookups on a near-full table, we resize the table when
  57. it's two-thirds full.
  58. */
  59. namespace Rml {
  60. namespace Core {
  61. /* See large comment block below. This must be >= 1. */
  62. #define PERTURB_SHIFT 5
  63. /* switch these defines if you want dumps all dictionary access */
  64. #define DICTIONARY_DEBUG_CODE(x)
  65. //#define DICTIONARY_DEBUG_CODE(x) x
  66. /*
  67. Major subtleties ahead: Most hash schemes depend on having a "good" hash
  68. function, in the sense of simulating randomness. Python doesn't: its most
  69. important hash functions (for strings and ints) are very regular in common
  70. cases:
  71. >>> map(hash, (0, 1, 2, 3))
  72. [0, 1, 2, 3]
  73. >>> map(hash, ("namea", "nameb", "namec", "named"))
  74. [-1658398457, -1658398460, -1658398459, -1658398462]
  75. >>>
  76. This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
  77. the low-order i bits as the initial table index is extremely fast, and there
  78. are no collisions at all for dicts indexed by a contiguous range of ints.
  79. The same is approximately true when keys are "consecutive" strings. So this
  80. gives better-than-random behavior in common cases, and that's very desirable.
  81. OTOH, when collisions occur, the tendency to fill contiguous slices of the
  82. hash table makes a good collision resolution strategy crucial. Taking only
  83. the last i bits of the hash code is also vulnerable: for example, consider
  84. [i << 16 for i in range(20000)] as a set of keys. Since ints are their own
  85. hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
  86. hash code are all 0: they *all* map to the same table index.
  87. But catering to unusual cases should not slow the usual ones, so we just take
  88. the last i bits anyway. It's up to collision resolution to do the rest. If
  89. we *usually* find the key we're looking for on the first try (and, it turns
  90. out, we usually do -- the table load factor is kept under 2/3, so the odds
  91. are solidly in our favor), then it makes best sense to keep the initial index
  92. computation dirt cheap.
  93. The first half of collision resolution is to visit table indices via this
  94. recurrence:
  95. j = ((5*j) + 1) mod 2**i
  96. For any initial j in range(2**i), repeating that 2**i times generates each
  97. int in range(2**i) exactly once (see any text on random-number generation for
  98. proof). By itself, this doesn't help much: like linear probing (setting
  99. j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
  100. order. This would be bad, except that's not the only thing we do, and it's
  101. actually *good* in the common cases where hash keys are consecutive. In an
  102. example that's really too small to make this entirely clear, for a table of
  103. size 2**3 the order of indices is:
  104. 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
  105. If two things come in at index 5, the first place we look after is index 2,
  106. not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
  107. Linear probing is deadly in this case because there the fixed probe order
  108. is the *same* as the order consecutive keys are likely to arrive. But it's
  109. extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
  110. and certain that consecutive hash codes do not.
  111. The other half of the strategy is to get the other bits of the hash code
  112. into play. This is done by initializing a (unsigned) vrbl "perturb" to the
  113. full hash code, and changing the recurrence to:
  114. j = (5*j) + 1 + perturb;
  115. perturb >>= PERTURB_SHIFT;
  116. use j % 2**i as the next table index;
  117. Now the probe sequence depends (eventually) on every bit in the hash code,
  118. and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
  119. because it quickly magnifies small differences in the bits that didn't affect
  120. the initial index. Note that because perturb is unsigned, if the recurrence
  121. is executed often enough perturb eventually becomes and remains 0. At that
  122. point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
  123. that's certain to find an empty slot eventually (since it generates every int
  124. in range(2**i), and we make sure there's always at least one empty slot).
  125. Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
  126. small so that the high bits of the hash code continue to affect the probe
  127. sequence across iterations; but you want it large so that in really bad cases
  128. the high-order hash bits have an effect on early iterations. 5 was "the
  129. best" in minimizing total collisions across experiments Tim Peters ran (on
  130. both normal and pathological cases), but 4 and 6 weren't significantly worse.
  131. Historical: Reimer Behrends contributed the idea of using a polynomial-based
  132. approach, using repeated multiplication by x in GF(2**n) where an irreducible
  133. polynomial for each table size was chosen such that x was a primitive root.
  134. Christian Tismer later extended that to use division by x instead, as an
  135. efficient way to get the high bits of the hash code into play. This scheme
  136. also gave excellent collision statistics, but was more expensive: two
  137. if-tests were required inside the loop; computing "the next" index took about
  138. the same number of operations but without as much potential parallelism
  139. (e.g., computing 5*j can go on at the same time as computing 1+perturb in the
  140. above, and then shifting perturb can be done while the table index is being
  141. masked); and the dictobject struct required a member to hold the table's
  142. polynomial. In Tim's experiments the current scheme ran faster, produced
  143. equally good collision statistics, needed less code & used less memory.
  144. */
  145. static String dummy_key = String(128, "###DUMMYRMLUIDICTKEY%d###", &dummy_key);
  146. Dictionary::Dictionary()
  147. {
  148. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS,"Dictionary::New Dict"); )
  149. ResetToMinimumSize();
  150. }
  151. Dictionary::Dictionary(const Dictionary &dict)
  152. {
  153. ResetToMinimumSize();
  154. Copy(dict);
  155. }
  156. Dictionary::~Dictionary()
  157. {
  158. Clear();
  159. }
  160. /*
  161. The basic lookup function used by all operations.
  162. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
  163. Open addressing is preferred over chaining since the link overhead for
  164. chaining would be substantial (100% with typical malloc overhead).
  165. The initial probe index is computed as hash mod the table size. Subsequent
  166. probe indices are computed as explained earlier.
  167. All arithmetic on hash should ignore overflow.
  168. (The details in this version are due to Tim Peters, building on many past
  169. contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
  170. Christian Tismer).
  171. This function must never return NULL; failures are indicated by returning
  172. a dictentry* for which the me_value field is NULL. Exceptions are never
  173. reported by this function, and outstanding exceptions are maintained.
  174. */
  175. /*
  176. * Hacked up version of lookdict which can assume keys are always strings;
  177. * this assumption allows testing for errors during PyObject_Compare() to
  178. * be dropped; string-string comparisons never raise exceptions. This also
  179. * means we don't need to go through PyObject_Compare(); we can always use
  180. * _PyString_Eq directly.
  181. *
  182. * This is valuable because the general-case error handling in lookdict() is
  183. * expensive, and dicts with pure-string keys are very common.
  184. */
  185. Dictionary::DictionaryEntry* Dictionary::Retrieve(const String& key, Hash hash) const
  186. {
  187. Hash i = 0;
  188. unsigned int perturb;
  189. DictionaryEntry *freeslot;
  190. unsigned int mask = this->mask;
  191. DictionaryEntry *ep0 = table;
  192. DictionaryEntry *ep;
  193. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Retreive %s", key); )
  194. /* Make sure this function doesn't have to handle non-string keys,
  195. including subclasses of str; e.g., one reason to subclass
  196. strings is to override __eq__, and for speed we don't cater to
  197. that here. */
  198. i = hash & mask;
  199. ep = &ep0[i];
  200. if (ep->key.Empty() || ep->key == key)
  201. return ep;
  202. if (ep->key == dummy_key)
  203. freeslot = ep;
  204. else {
  205. if (ep->hash == hash && ep->key == key) {
  206. return ep;
  207. }
  208. freeslot = NULL;
  209. }
  210. /* In the loop, me_key == dummy_key is by far (factor of 100s) the
  211. least likely outcome, so test for that last. */
  212. for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
  213. i = (i << 2) + i + perturb + 1;
  214. ep = &ep0[i & mask];
  215. if (ep->key.Empty())
  216. return freeslot == NULL ? ep : freeslot;
  217. /*if (ep->me_key == key
  218. || (ep->me_hash == hash
  219. && ep->me_key != dummy_key
  220. && _PyString_Eq(ep->me_key, key)))*/
  221. if (ep->key == key)
  222. return ep;
  223. if (ep->key == dummy_key && freeslot == NULL)
  224. freeslot = ep;
  225. }
  226. }
  227. /*
  228. Internal routine to insert a new item into the table.
  229. Used both by the internal resize routine and by the public insert routine.
  230. */
  231. void Dictionary::Insert(const String& key, Hash hash, const Variant& value)
  232. {
  233. DictionaryEntry *ep;
  234. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Insert %s", key); );
  235. ep = Retrieve(key, hash);
  236. if (ep->value.GetType() !=Variant::NONE)
  237. {
  238. ep->value = value;
  239. }
  240. else
  241. {
  242. if (ep->key.Empty())
  243. {
  244. num_full++;
  245. }
  246. else if ( ep->key != dummy_key )
  247. {
  248. //delete ep->key;
  249. }
  250. ep->key = key;
  251. ep->hash = hash;
  252. ep->value = value;
  253. num_used++;
  254. }
  255. }
  256. /*
  257. Restructure the table by allocating a new table and reinserting all
  258. items again. When entries have been deleted, the new table may
  259. actually be smaller than the old one.
  260. */
  261. bool Dictionary::Reserve(int minused)
  262. {
  263. int newsize;
  264. DictionaryEntry *oldtable, *newtable, *ep;
  265. int i = 0;
  266. bool is_oldtable_malloced;
  267. DictionaryEntry small_copy[DICTIONARY_MINSIZE];
  268. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Reserve %d", minused); )
  269. RMLUI_ASSERT(minused >= 0);
  270. /* Find the smallest table size > minused. */
  271. newsize = DICTIONARY_MINSIZE;
  272. while(newsize <= minused) {
  273. newsize <<= 1; // double the table size and test again
  274. if(newsize <= 0) {
  275. RMLUI_ASSERT(newsize > 0);
  276. return false; // newsize has overflowed the max size for this platform, abort
  277. }
  278. }
  279. // If its the same size, ignore the request
  280. if ((unsigned)newsize == mask + 1)
  281. return true;
  282. /* Get space for a new table. */
  283. oldtable = table;
  284. RMLUI_ASSERT(oldtable != NULL);
  285. is_oldtable_malloced = oldtable != small_table;
  286. if (newsize == DICTIONARY_MINSIZE) {
  287. /* A large table is shrinking, or we can't get any smaller. */
  288. newtable = small_table;
  289. if (newtable == oldtable) {
  290. if (num_full == num_used) {
  291. /* No dummies, so no point doing anything. */
  292. return true;
  293. }
  294. /* We're not going to resize it, but rebuild the
  295. table anyway to purge old dummy_key entries.
  296. Subtle: This is *necessary* if fill==size,
  297. as lookdict needs at least one virgin slot to
  298. terminate failing searches. If fill < size, it's
  299. merely desirable, as dummies slow searches. */
  300. RMLUI_ASSERT(num_full > num_used);
  301. memcpy(small_copy, oldtable, sizeof(small_copy));
  302. oldtable = small_copy;
  303. }
  304. } else {
  305. newtable = new DictionaryEntry[newsize];
  306. RMLUI_ASSERT(newtable);
  307. if (newtable == NULL) {
  308. return false;
  309. }
  310. }
  311. /* Make the dict empty, using the new table. */
  312. RMLUI_ASSERT(newtable != oldtable);
  313. table = newtable;
  314. mask = newsize - 1;
  315. //memset(newtable, 0, sizeof(DictionaryEntry) * newsize);
  316. num_used = 0;
  317. i = num_full;
  318. num_full = 0;
  319. /* Copy the data over; this is refcount-neutral for active entries;
  320. dummy_key entries aren't copied over, of course */
  321. for (ep = oldtable; i > 0; ep++) {
  322. if (ep->value.GetType() != Variant::NONE) { /* active entry */
  323. --i;
  324. Insert(ep->key, ep->hash, ep->value);
  325. //delete[] ep->key;
  326. }
  327. else if (!ep->key.Empty()) { /* dummy_key entry */
  328. --i;
  329. RMLUI_ASSERT(ep->key == dummy_key);
  330. }
  331. /* else key == value == NULL: nothing to do */
  332. }
  333. if (is_oldtable_malloced)
  334. delete[] oldtable;
  335. return true;
  336. }
  337. Variant* Dictionary::Get(const String& key) const
  338. {
  339. Hash hash;
  340. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Get %s", key); );
  341. hash = StringUtilities::FNVHash( key.CString() );
  342. DictionaryEntry* result = Retrieve(key, hash);
  343. if (!result || result->key.Empty() || result->key == dummy_key)
  344. {
  345. return NULL;
  346. }
  347. return &result->value;
  348. }
  349. Variant* Dictionary::operator[](const String& key) const
  350. {
  351. return Get(key);
  352. }
  353. /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
  354. * dictionary if it is merely replacing the value for an existing key.
  355. * This is means that it's safe to loop over a dictionary with
  356. * PyDict_Next() and occasionally replace a value -- but you can't
  357. * insert new keys or remove them.
  358. */
  359. void Dictionary::Set(const String& key, const Variant &value)
  360. {
  361. if (key.Empty())
  362. {
  363. Log::Message(Log::LT_WARNING, "Unable to set value on dictionary, empty key specified.");
  364. return;
  365. }
  366. Hash hash;
  367. unsigned int n_used;
  368. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Set %s", key); );
  369. hash = StringUtilities::FNVHash( key.CString() );
  370. RMLUI_ASSERT(num_full <= mask); /* at least one empty slot */
  371. n_used = num_used;
  372. Insert( key, hash, value );
  373. /* If we added a key, we can safely resize. Otherwise skip this!
  374. * If fill >= 2/3 size, adjust size. Normally, this doubles the
  375. * size, but it's also possible for the dict to shrink (if ma_fill is
  376. * much larger than ma_used, meaning a lot of dict keys have been
  377. * deleted).
  378. */
  379. if ((num_used > n_used) && (num_full * 3) >= (mask + 1) * 2)
  380. {
  381. if (!Reserve(num_used * 2))
  382. {
  383. Log::Message(Log::LT_ALWAYS, "Dictionary::Error resizing dictionary after insert");
  384. }
  385. }
  386. }
  387. bool Dictionary::Remove(const String& key)
  388. {
  389. Hash hash;
  390. DictionaryEntry *ep;
  391. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Remove %s", key) );
  392. hash = StringUtilities::FNVHash( key.CString() );
  393. ep = Retrieve(key, hash);
  394. if (ep->value.GetType() == Variant::NONE)
  395. {
  396. return false;
  397. }
  398. ep->key = dummy_key;
  399. ep->value.Clear();
  400. num_used--;
  401. return true;
  402. }
  403. void Dictionary::Clear()
  404. {
  405. DictionaryEntry *ep;
  406. bool table_is_malloced;
  407. int n_full;
  408. int i, n;
  409. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Clear") );
  410. n = mask + 1;
  411. i = 0;
  412. table_is_malloced = table != small_table;
  413. n_full = num_full;
  414. // Clear things up
  415. for (ep = table; n_full > 0; ++ep) {
  416. RMLUI_ASSERT(i < n);
  417. ++i;
  418. if (!ep->key.Empty()) {
  419. --n_full;
  420. ep->key.Clear();
  421. ep->value.Clear();
  422. } else {
  423. RMLUI_ASSERT(ep->value.GetType() == Variant::NONE);
  424. }
  425. }
  426. if (table_is_malloced)
  427. delete [] table;
  428. ResetToMinimumSize();
  429. }
  430. bool Dictionary::IsEmpty() const
  431. {
  432. return num_used == 0;
  433. }
  434. int Dictionary::Size() const
  435. {
  436. return num_used;
  437. }
  438. // Merges another dictionary into this one. Any existing values stored against similar keys will be updated.
  439. void Dictionary::Merge(const Dictionary& dict)
  440. {
  441. int index = 0;
  442. String key;
  443. Variant* value;
  444. while (dict.Iterate(index, key, value))
  445. {
  446. Set(key, *value);
  447. }
  448. }
  449. /* CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
  450. * mutates the dict. One exception: it is safe if the loop merely changes
  451. * the values associated with the keys (but doesn't insert new keys or
  452. * delete keys), via PyDict_SetItem().
  453. */
  454. bool Dictionary::Iterate(int &pos, String& key, Variant* &value) const
  455. {
  456. unsigned int i;
  457. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Next %d", pos); )
  458. i = pos;
  459. while (i <= mask && table[i].value.GetType() == Variant::NONE)
  460. i++;
  461. pos = i+1;
  462. if (i > mask)
  463. return false;
  464. key = table[i].key;
  465. value = &table[i].value;
  466. return true;
  467. }
  468. void Dictionary::operator=(const Dictionary &dict) {
  469. Copy(dict);
  470. }
  471. void Dictionary::Copy(const Dictionary &dict) {
  472. unsigned int i;
  473. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::Copy Dict (Size: %d)", dict.num_used); )
  474. // Clear our current state
  475. Clear();
  476. // Resize our table
  477. Reserve(dict.mask);
  478. // Copy elements across
  479. for ( i = 0; i < dict.mask + 1; i++ )
  480. {
  481. table[i].hash = dict.table[i].hash;
  482. table[i].key = dict.table[i].key;
  483. table[i].value = dict.table[i].value;
  484. }
  485. // Set properties
  486. num_used = dict.num_used;
  487. num_full = dict.num_full;
  488. mask = dict.mask;
  489. }
  490. void Dictionary::ResetToMinimumSize()
  491. {
  492. DICTIONARY_DEBUG_CODE( Log::Message(LC_CORE, Log::LT_ALWAYS, "Dictionary::ResetToMinimumSize"); )
  493. // Reset to small table
  494. for ( size_t i = 0; i < DICTIONARY_MINSIZE; i++ )
  495. {
  496. small_table[i].hash = 0;
  497. small_table[i].key.Clear();
  498. small_table[i].value.Clear();
  499. }
  500. num_used = 0;
  501. num_full = 0;
  502. table = small_table;
  503. mask = DICTIONARY_MINSIZE - 1;
  504. }
  505. }
  506. }