base.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #pragma once
  2. #include "pocketpy/common/types.hpp"
  3. #include "pocketpy/common/traits.hpp"
  4. #include "pocketpy/objects/base.h"
  5. #include <cstddef>
  6. #include <cstdint>
  7. #include <cassert>
  8. #include <cstdlib>
  9. #include <cstring>
  10. namespace pkpy {
  11. struct Type {
  12. pkpy_Type index;
  13. constexpr Type() : index(0) {}
  14. constexpr Type(pkpy_Type index) : index(index) {}
  15. bool operator== (Type other) const { return this->index == other.index; }
  16. bool operator!= (Type other) const { return this->index != other.index; }
  17. constexpr operator pkpy_Type () const { return index; }
  18. };
  19. struct PyVar final: ::PyVar {
  20. // uninitialized
  21. PyVar() = default;
  22. // implict conversion
  23. PyVar(PyObject* existing){
  24. PyVar__ctor3(this, (::PyObject*)existing);
  25. }
  26. /* We must initialize all members to allow == operator to work correctly */
  27. // zero initialized
  28. PyVar(std::nullptr_t){
  29. set_null();
  30. }
  31. // PyObject* initialized (is_sso = false)
  32. PyVar(Type type, PyObject* p){
  33. PyVar__ctor(this, type, (::PyObject*)p);
  34. }
  35. PyVar(Type type, i64 value){
  36. this->type = type;
  37. this->is_ptr = false;
  38. this->_i64 = value;
  39. }
  40. explicit operator bool () const { return (bool)type; }
  41. void set_null() {
  42. memset(this, 0, sizeof(PyVar));
  43. }
  44. bool operator==(PyObject* other){
  45. return is_ptr && (PyObject*)_obj == other;
  46. }
  47. bool operator!=(PyObject* other){
  48. return !is_ptr || (PyObject*)_obj != other;
  49. }
  50. bool operator==(std::nullptr_t){
  51. return type == 0;
  52. }
  53. bool operator!=(std::nullptr_t){
  54. return type != 0;
  55. }
  56. PyObject* get() const {
  57. assert(is_ptr);
  58. return (PyObject*)_obj;
  59. }
  60. PyObject* operator->() const {
  61. assert(is_ptr);
  62. return (PyObject*)_obj;
  63. }
  64. i64 hash() const { return PyVar__hash(this); }
  65. template <typename T>
  66. obj_get_t<T> obj_get();
  67. // implicit convert from ::PyVar
  68. PyVar(const ::PyVar& var) {
  69. memcpy(this, &var, sizeof(var));
  70. }
  71. };
  72. static_assert(sizeof(PyVar) == 16 && is_pod_v<PyVar>);
  73. } // namespace pkpy