map.c 15 KB

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