cast.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "pocketpy/objects/base.h"
  2. #include "pocketpy/pocketpy.h"
  3. #include "pocketpy/objects/object.h"
  4. #include "pocketpy/interpreter/vm.h"
  5. int64_t py_toint(py_Ref self) {
  6. assert(self->type == tp_int);
  7. return self->_i64;
  8. }
  9. void* py_totrivial(py_Ref self) { return &self->_chars; }
  10. double py_tofloat(py_Ref self) {
  11. assert(self->type == tp_float);
  12. return self->_f64;
  13. }
  14. bool py_castfloat(py_Ref self, double* out) {
  15. switch(self->type) {
  16. case tp_int: *out = (double)self->_i64; return true;
  17. case tp_float: *out = self->_f64; return true;
  18. default: return TypeError("expected 'int' or 'float', got '%t'", self->type);
  19. }
  20. }
  21. bool py_castfloat32(py_Ref self, float* out) {
  22. switch(self->type) {
  23. case tp_int: *out = (float)self->_i64; return true;
  24. case tp_float: *out = (float)self->_f64; return true;
  25. default: return TypeError("expected 'int' or 'float', got '%t'", self->type);
  26. }
  27. }
  28. bool py_castint(py_Ref self, int64_t* out) {
  29. if(self->type == tp_int) {
  30. *out = self->_i64;
  31. return true;
  32. }
  33. return TypeError("expected 'int', got '%t'", self->type);
  34. }
  35. bool py_tobool(py_Ref self) {
  36. assert(self->type == tp_bool);
  37. return self->_bool;
  38. }
  39. py_Type py_totype(py_Ref self) {
  40. assert(self->type == tp_type);
  41. py_TypeInfo* ud = py_touserdata(self);
  42. return ud->index;
  43. }
  44. void* py_touserdata(py_Ref self) {
  45. assert(self && self->is_ptr);
  46. return PyObject__userdata(self->_obj);
  47. }