dict.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. PyVar first;
  10. PyVar second;
  11. int prev;
  12. int next;
  13. };
  14. static constexpr int __Capacity = 8;
  15. static constexpr float __LoadFactor = 0.67f;
  16. int _capacity;
  17. int _mask;
  18. int _size;
  19. int _critical_size;
  20. int _head_idx; // for order preserving
  21. int _tail_idx; // for order preserving
  22. Item* _items;
  23. Dict();
  24. Dict(Dict&& other);
  25. Dict(const Dict& other);
  26. Dict& operator=(const Dict&) = delete;
  27. Dict& operator=(Dict&&) = delete;
  28. int size() const { return _size; }
  29. void _probe_0(VM* vm, PyVar key, bool& ok, int& i) const;
  30. void _probe_1(VM* vm, PyVar key, bool& ok, int& i) const;
  31. void set(VM* vm, PyVar key, PyVar val);
  32. void _rehash(VM* vm);
  33. PyVar try_get(VM* vm, PyVar key) const;
  34. bool contains(VM* vm, PyVar key) const;
  35. bool del(VM* vm, PyVar key);
  36. void update(VM* vm, const Dict& other);
  37. template<typename __Func>
  38. void apply(__Func f) const {
  39. int i = _head_idx;
  40. while(i != -1){
  41. f(_items[i].first, _items[i].second);
  42. i = _items[i].next;
  43. }
  44. }
  45. Tuple keys() const;
  46. Tuple values() const;
  47. void clear();
  48. ~Dict();
  49. void __alloc_items();
  50. void _gc_mark(VM*) const;
  51. };
  52. } // namespace pkpy