map.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  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. #include <stdint.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <assert.h>
  30. #include "py/mpconfig.h"
  31. #include "py/misc.h"
  32. #include "py/runtime.h"
  33. #if MICROPY_DEBUG_VERBOSE // print debugging info
  34. #define DEBUG_PRINT (1)
  35. #else // don't print debugging info
  36. #define DEBUG_PRINT (0)
  37. #define DEBUG_printf(...) (void)0
  38. #endif
  39. #if MICROPY_OPT_MAP_LOOKUP_CACHE
  40. // MP_STATE_VM(map_lookup_cache) provides a cache of index to the last known
  41. // position of that index in any map. On a cache hit, this allows
  42. // short-circuiting the full linear search in the case of an ordered map
  43. // (i.e. all builtin modules and objects' locals dicts), and computation of
  44. // the hash (and potentially some linear probing) in the case of a regular
  45. // map. Note the same cache is shared across all maps.
  46. // Gets the index into the cache for this index. Shift down by two to remove
  47. // mp_obj_t tag bits.
  48. #define MAP_CACHE_OFFSET(index) ((((uintptr_t)(index)) >> 2) % MICROPY_OPT_MAP_LOOKUP_CACHE_SIZE)
  49. // Gets the map cache entry for the corresponding index.
  50. #define MAP_CACHE_ENTRY(index) (MP_STATE_VM(map_lookup_cache)[MAP_CACHE_OFFSET(index)])
  51. // Retrieve the mp_obj_t at the location suggested by the cache.
  52. #define MAP_CACHE_GET(map, index) (&(map)->table[MAP_CACHE_ENTRY(index) % (map)->alloc])
  53. // Update the cache for this index.
  54. #define MAP_CACHE_SET(index, pos) MAP_CACHE_ENTRY(index) = (pos) & 0xff;
  55. #else
  56. #define MAP_CACHE_SET(index, pos)
  57. #endif
  58. // This table of sizes is used to control the growth of hash tables.
  59. // The first set of sizes are chosen so the allocation fits exactly in a
  60. // 4-word GC block, and it's not so important for these small values to be
  61. // prime. The latter sizes are prime and increase at an increasing rate.
  62. static const uint16_t hash_allocation_sizes[] = {
  63. 0, 2, 4, 6, 8, 10, 12, // +2
  64. 17, 23, 29, 37, 47, 59, 73, // *1.25
  65. 97, 127, 167, 223, 293, 389, 521, 691, 919, 1223, 1627, 2161, // *1.33
  66. 3229, 4831, 7243, 10861, 16273, 24407, 36607, 54907, // *1.5
  67. };
  68. static size_t get_hash_alloc_greater_or_equal_to(size_t x) {
  69. for (size_t i = 0; i < MP_ARRAY_SIZE(hash_allocation_sizes); i++) {
  70. if (hash_allocation_sizes[i] >= x) {
  71. return hash_allocation_sizes[i];
  72. }
  73. }
  74. // ran out of primes in the table!
  75. // return something sensible, at least make it odd
  76. return (x + x / 2) | 1;
  77. }
  78. /******************************************************************************/
  79. /* map */
  80. void mp_map_init(mp_map_t *map, size_t n) {
  81. if (n == 0) {
  82. map->alloc = 0;
  83. map->table = NULL;
  84. } else {
  85. map->alloc = n;
  86. map->table = m_new0(mp_map_elem_t, map->alloc);
  87. }
  88. map->used = 0;
  89. map->all_keys_are_qstrs = 1;
  90. map->is_fixed = 0;
  91. map->is_ordered = 0;
  92. }
  93. void mp_map_init_fixed_table(mp_map_t *map, size_t n, const mp_obj_t *table) {
  94. map->alloc = n;
  95. map->used = n;
  96. map->all_keys_are_qstrs = 1;
  97. map->is_fixed = 1;
  98. map->is_ordered = 1;
  99. map->table = (mp_map_elem_t *)table;
  100. }
  101. // Differentiate from mp_map_clear() - semantics is different
  102. void mp_map_deinit(mp_map_t *map) {
  103. if (!map->is_fixed) {
  104. m_del(mp_map_elem_t, map->table, map->alloc);
  105. }
  106. map->used = map->alloc = 0;
  107. }
  108. void mp_map_clear(mp_map_t *map) {
  109. if (!map->is_fixed) {
  110. m_del(mp_map_elem_t, map->table, map->alloc);
  111. }
  112. map->alloc = 0;
  113. map->used = 0;
  114. map->all_keys_are_qstrs = 1;
  115. map->is_fixed = 0;
  116. map->table = NULL;
  117. }
  118. static void mp_map_rehash(mp_map_t *map) {
  119. size_t old_alloc = map->alloc;
  120. size_t new_alloc = get_hash_alloc_greater_or_equal_to(map->alloc + 1);
  121. DEBUG_printf("mp_map_rehash(%p): " UINT_FMT " -> " UINT_FMT "\n", map, old_alloc, new_alloc);
  122. mp_map_elem_t *old_table = map->table;
  123. mp_map_elem_t *new_table = m_new0(mp_map_elem_t, new_alloc);
  124. // If we reach this point, table resizing succeeded, now we can edit the old map.
  125. map->alloc = new_alloc;
  126. map->used = 0;
  127. map->all_keys_are_qstrs = 1;
  128. map->table = new_table;
  129. for (size_t i = 0; i < old_alloc; i++) {
  130. if (old_table[i].key != MP_OBJ_NULL && old_table[i].key != MP_OBJ_SENTINEL) {
  131. mp_map_lookup(map, old_table[i].key, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = old_table[i].value;
  132. }
  133. }
  134. m_del(mp_map_elem_t, old_table, old_alloc);
  135. }
  136. // MP_MAP_LOOKUP behaviour:
  137. // - returns NULL if not found, else the slot it was found in with key,value non-null
  138. // MP_MAP_LOOKUP_ADD_IF_NOT_FOUND behaviour:
  139. // - returns slot, with key non-null and value=MP_OBJ_NULL if it was added
  140. // MP_MAP_LOOKUP_REMOVE_IF_FOUND behaviour:
  141. // - returns NULL if not found, else the slot if was found in with key null and value non-null
  142. mp_map_elem_t *MICROPY_WRAP_MP_MAP_LOOKUP(mp_map_lookup)(mp_map_t * map, mp_obj_t index, mp_map_lookup_kind_t lookup_kind) {
  143. // If the map is a fixed array then we must only be called for a lookup
  144. assert(!map->is_fixed || lookup_kind == MP_MAP_LOOKUP);
  145. #if MICROPY_OPT_MAP_LOOKUP_CACHE
  146. // Try the cache for lookup or add-if-not-found.
  147. if (lookup_kind != MP_MAP_LOOKUP_REMOVE_IF_FOUND && map->alloc) {
  148. mp_map_elem_t *slot = MAP_CACHE_GET(map, index);
  149. // Note: Just comparing key for value equality will have false negatives, but
  150. // these will be handled by the regular path below.
  151. if (slot->key == index) {
  152. return slot;
  153. }
  154. }
  155. #endif
  156. // Work out if we can compare just pointers
  157. bool compare_only_ptrs = map->all_keys_are_qstrs;
  158. if (compare_only_ptrs) {
  159. if (mp_obj_is_qstr(index)) {
  160. // Index is a qstr, so can just do ptr comparison.
  161. } else if (mp_obj_is_exact_type(index, &mp_type_str)) {
  162. // Index is a non-interned string.
  163. // We can either intern the string, or force a full equality comparison.
  164. // We chose the latter, since interning costs time and potentially RAM,
  165. // and it won't necessarily benefit subsequent calls because these calls
  166. // most likely won't pass the newly-interned string.
  167. compare_only_ptrs = false;
  168. } else if (lookup_kind != MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) {
  169. // If we are not adding, then we can return straight away a failed
  170. // lookup because we know that the index will never be found.
  171. return NULL;
  172. }
  173. }
  174. // if the map is an ordered array then we must do a brute force linear search
  175. if (map->is_ordered) {
  176. for (mp_map_elem_t *elem = &map->table[0], *top = &map->table[map->used]; elem < top; elem++) {
  177. if (elem->key == index || (!compare_only_ptrs && mp_obj_equal(elem->key, index))) {
  178. #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
  179. if (MP_UNLIKELY(lookup_kind == MP_MAP_LOOKUP_REMOVE_IF_FOUND)) {
  180. // remove the found element by moving the rest of the array down
  181. mp_obj_t value = elem->value;
  182. --map->used;
  183. memmove(elem, elem + 1, (top - elem - 1) * sizeof(*elem));
  184. // put the found element after the end so the caller can access it if needed
  185. // note: caller must NULL the value so the GC can clean up (e.g. see dict_get_helper).
  186. elem = &map->table[map->used];
  187. elem->key = MP_OBJ_NULL;
  188. elem->value = value;
  189. }
  190. #endif
  191. MAP_CACHE_SET(index, elem - map->table);
  192. return elem;
  193. }
  194. }
  195. #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
  196. if (MP_LIKELY(lookup_kind != MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)) {
  197. return NULL;
  198. }
  199. if (map->used == map->alloc) {
  200. // TODO: Alloc policy
  201. map->alloc += 4;
  202. map->table = m_renew(mp_map_elem_t, map->table, map->used, map->alloc);
  203. mp_seq_clear(map->table, map->used, map->alloc, sizeof(*map->table));
  204. }
  205. mp_map_elem_t *elem = map->table + map->used++;
  206. elem->key = index;
  207. elem->value = MP_OBJ_NULL;
  208. if (!mp_obj_is_qstr(index)) {
  209. map->all_keys_are_qstrs = 0;
  210. }
  211. return elem;
  212. #else
  213. return NULL;
  214. #endif
  215. }
  216. // map is a hash table (not an ordered array), so do a hash lookup
  217. if (map->alloc == 0) {
  218. if (lookup_kind == MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) {
  219. mp_map_rehash(map);
  220. } else {
  221. return NULL;
  222. }
  223. }
  224. // get hash of index, with fast path for common case of qstr
  225. mp_uint_t hash;
  226. if (mp_obj_is_qstr(index)) {
  227. hash = qstr_hash(MP_OBJ_QSTR_VALUE(index));
  228. } else {
  229. hash = MP_OBJ_SMALL_INT_VALUE(mp_unary_op(MP_UNARY_OP_HASH, index));
  230. }
  231. size_t pos = hash % map->alloc;
  232. size_t start_pos = pos;
  233. mp_map_elem_t *avail_slot = NULL;
  234. for (;;) {
  235. mp_map_elem_t *slot = &map->table[pos];
  236. if (slot->key == MP_OBJ_NULL) {
  237. // found NULL slot, so index is not in table
  238. if (lookup_kind == MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) {
  239. map->used += 1;
  240. if (avail_slot == NULL) {
  241. avail_slot = slot;
  242. }
  243. avail_slot->key = index;
  244. avail_slot->value = MP_OBJ_NULL;
  245. if (!mp_obj_is_qstr(index)) {
  246. map->all_keys_are_qstrs = 0;
  247. }
  248. return avail_slot;
  249. } else {
  250. return NULL;
  251. }
  252. } else if (slot->key == MP_OBJ_SENTINEL) {
  253. // found deleted slot, remember for later
  254. if (avail_slot == NULL) {
  255. avail_slot = slot;
  256. }
  257. } else if (slot->key == index || (!compare_only_ptrs && mp_obj_equal(slot->key, index))) {
  258. // found index
  259. // Note: CPython does not replace the index; try x={True:'true'};x[1]='one';x
  260. if (lookup_kind == MP_MAP_LOOKUP_REMOVE_IF_FOUND) {
  261. // delete element in this slot
  262. map->used--;
  263. if (map->table[(pos + 1) % map->alloc].key == MP_OBJ_NULL) {
  264. // optimisation if next slot is empty
  265. slot->key = MP_OBJ_NULL;
  266. } else {
  267. slot->key = MP_OBJ_SENTINEL;
  268. }
  269. // keep slot->value so that caller can access it if needed
  270. }
  271. MAP_CACHE_SET(index, pos);
  272. return slot;
  273. }
  274. // not yet found, keep searching in this table
  275. pos = (pos + 1) % map->alloc;
  276. if (pos == start_pos) {
  277. // search got back to starting position, so index is not in table
  278. if (lookup_kind == MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) {
  279. if (avail_slot != NULL) {
  280. // there was an available slot, so use that
  281. map->used++;
  282. avail_slot->key = index;
  283. avail_slot->value = MP_OBJ_NULL;
  284. if (!mp_obj_is_qstr(index)) {
  285. map->all_keys_are_qstrs = 0;
  286. }
  287. return avail_slot;
  288. } else {
  289. // not enough room in table, rehash it
  290. mp_map_rehash(map);
  291. // restart the search for the new element
  292. start_pos = pos = hash % map->alloc;
  293. }
  294. } else {
  295. return NULL;
  296. }
  297. }
  298. }
  299. }
  300. /******************************************************************************/
  301. /* set */
  302. #if MICROPY_PY_BUILTINS_SET
  303. void mp_set_init(mp_set_t *set, size_t n) {
  304. set->alloc = n;
  305. set->used = 0;
  306. set->table = m_new0(mp_obj_t, set->alloc);
  307. }
  308. static void mp_set_rehash(mp_set_t *set) {
  309. size_t old_alloc = set->alloc;
  310. mp_obj_t *old_table = set->table;
  311. set->alloc = get_hash_alloc_greater_or_equal_to(set->alloc + 1);
  312. set->used = 0;
  313. set->table = m_new0(mp_obj_t, set->alloc);
  314. for (size_t i = 0; i < old_alloc; i++) {
  315. if (old_table[i] != MP_OBJ_NULL && old_table[i] != MP_OBJ_SENTINEL) {
  316. mp_set_lookup(set, old_table[i], MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
  317. }
  318. }
  319. m_del(mp_obj_t, old_table, old_alloc);
  320. }
  321. mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, mp_map_lookup_kind_t lookup_kind) {
  322. // Note: lookup_kind can be MP_MAP_LOOKUP_ADD_IF_NOT_FOUND_OR_REMOVE_IF_FOUND which
  323. // is handled by using bitwise operations.
  324. if (set->alloc == 0) {
  325. if (lookup_kind & MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) {
  326. mp_set_rehash(set);
  327. } else {
  328. return MP_OBJ_NULL;
  329. }
  330. }
  331. mp_uint_t hash = MP_OBJ_SMALL_INT_VALUE(mp_unary_op(MP_UNARY_OP_HASH, index));
  332. size_t pos = hash % set->alloc;
  333. size_t start_pos = pos;
  334. mp_obj_t *avail_slot = NULL;
  335. for (;;) {
  336. mp_obj_t elem = set->table[pos];
  337. if (elem == MP_OBJ_NULL) {
  338. // found NULL slot, so index is not in table
  339. if (lookup_kind & MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) {
  340. if (avail_slot == NULL) {
  341. avail_slot = &set->table[pos];
  342. }
  343. set->used++;
  344. *avail_slot = index;
  345. return index;
  346. } else {
  347. return MP_OBJ_NULL;
  348. }
  349. } else if (elem == MP_OBJ_SENTINEL) {
  350. // found deleted slot, remember for later
  351. if (avail_slot == NULL) {
  352. avail_slot = &set->table[pos];
  353. }
  354. } else if (mp_obj_equal(elem, index)) {
  355. // found index
  356. if (lookup_kind & MP_MAP_LOOKUP_REMOVE_IF_FOUND) {
  357. // delete element
  358. set->used--;
  359. if (set->table[(pos + 1) % set->alloc] == MP_OBJ_NULL) {
  360. // optimisation if next slot is empty
  361. set->table[pos] = MP_OBJ_NULL;
  362. } else {
  363. set->table[pos] = MP_OBJ_SENTINEL;
  364. }
  365. }
  366. return elem;
  367. }
  368. // not yet found, keep searching in this table
  369. pos = (pos + 1) % set->alloc;
  370. if (pos == start_pos) {
  371. // search got back to starting position, so index is not in table
  372. if (lookup_kind & MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) {
  373. if (avail_slot != NULL) {
  374. // there was an available slot, so use that
  375. set->used++;
  376. *avail_slot = index;
  377. return index;
  378. } else {
  379. // not enough room in table, rehash it
  380. mp_set_rehash(set);
  381. // restart the search for the new element
  382. start_pos = pos = hash % set->alloc;
  383. }
  384. } else {
  385. return MP_OBJ_NULL;
  386. }
  387. }
  388. }
  389. }
  390. mp_obj_t mp_set_remove_first(mp_set_t *set) {
  391. for (size_t pos = 0; pos < set->alloc; pos++) {
  392. if (mp_set_slot_is_filled(set, pos)) {
  393. mp_obj_t elem = set->table[pos];
  394. // delete element
  395. set->used--;
  396. if (set->table[(pos + 1) % set->alloc] == MP_OBJ_NULL) {
  397. // optimisation if next slot is empty
  398. set->table[pos] = MP_OBJ_NULL;
  399. } else {
  400. set->table[pos] = MP_OBJ_SENTINEL;
  401. }
  402. return elem;
  403. }
  404. }
  405. return MP_OBJ_NULL;
  406. }
  407. void mp_set_clear(mp_set_t *set) {
  408. m_del(mp_obj_t, set->table, set->alloc);
  409. set->alloc = 0;
  410. set->used = 0;
  411. set->table = NULL;
  412. }
  413. #endif // MICROPY_PY_BUILTINS_SET
  414. #if defined(DEBUG_PRINT) && DEBUG_PRINT
  415. void mp_map_dump(mp_map_t *map) {
  416. for (size_t i = 0; i < map->alloc; i++) {
  417. if (map->table[i].key != MP_OBJ_NULL) {
  418. mp_obj_print(map->table[i].key, PRINT_REPR);
  419. } else {
  420. DEBUG_printf("(nil)");
  421. }
  422. DEBUG_printf(": %p\n", map->table[i].value);
  423. }
  424. DEBUG_printf("---\n");
  425. }
  426. #endif