dict.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #pragma once
  2. #include "obj.h"
  3. #include "common.h"
  4. #include "memory.h"
  5. #include "str.h"
  6. namespace pkpy{
  7. struct Dict{
  8. struct Item{
  9. PyObject* first;
  10. PyObject* second;
  11. };
  12. struct ItemNode{
  13. int prev;
  14. int next;
  15. };
  16. static constexpr int __Capacity = 8;
  17. static constexpr float __LoadFactor = 0.67f;
  18. static_assert(sizeof(Item) * __Capacity <= 128);
  19. static_assert(sizeof(ItemNode) * __Capacity <= 64);
  20. VM* vm;
  21. int _capacity;
  22. int _mask;
  23. int _size;
  24. int _critical_size;
  25. int _head_idx; // for order preserving
  26. int _tail_idx; // for order preserving
  27. Item* _items;
  28. ItemNode* _nodes; // for order preserving
  29. Dict(VM* vm);
  30. Dict(Dict&& other);
  31. Dict(const Dict& other);
  32. Dict& operator=(const Dict&) = delete;
  33. Dict& operator=(Dict&&) = delete;
  34. int size() const { return _size; }
  35. void _probe_0(PyObject* key, bool& ok, int& i) const;
  36. void _probe_1(PyObject* key, bool& ok, int& i) const;
  37. void set(PyObject* key, PyObject* val);
  38. void _rehash();
  39. PyObject* try_get(PyObject* key) const;
  40. bool contains(PyObject* key) const;
  41. bool erase(PyObject* key);
  42. void update(const Dict& other);
  43. template<typename __Func>
  44. void apply(__Func f) const {
  45. int i = _head_idx;
  46. while(i != -1){
  47. f(_items[i].first, _items[i].second);
  48. i = _nodes[i].next;
  49. }
  50. }
  51. Tuple keys() const;
  52. Tuple values() const;
  53. void clear();
  54. ~Dict();
  55. void _gc_mark() const;
  56. };
  57. } // namespace pkpy