Dictionary.cpp 19 KB

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