tuplelist.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include "common.h"
  3. #include "memory.h"
  4. #include "str.h"
  5. namespace pkpy {
  6. using List = std::vector<PyObject*>;
  7. class Args {
  8. inline static THREAD_LOCAL FreeListA<PyObject*, 10, false> _pool;
  9. PyObject** _args;
  10. int _size;
  11. void _alloc(int n){
  12. this->_args = (n==0) ? nullptr : _pool.alloc(n);
  13. this->_size = n;
  14. }
  15. public:
  16. Args(int n){ _alloc(n); }
  17. Args(const Args& other){
  18. _alloc(other._size);
  19. for(int i=0; i<_size; i++) _args[i] = other._args[i];
  20. }
  21. Args(Args&& other) noexcept {
  22. this->_args = other._args;
  23. this->_size = other._size;
  24. other._args = nullptr;
  25. other._size = 0;
  26. }
  27. Args(std::initializer_list<PyObject*> list) : Args(list.size()){
  28. int i = 0;
  29. for(PyObject* p : list) _args[i++] = p;
  30. }
  31. Args(List&& other) noexcept : Args(other.size()){
  32. for(int i=0; i<_size; i++) _args[i] = other[i];
  33. other.clear();
  34. }
  35. PyObject*& operator[](int i){ return _args[i]; }
  36. PyObject* operator[](int i) const { return _args[i]; }
  37. Args& operator=(Args&& other) noexcept {
  38. _pool.dealloc(_args, _size);
  39. this->_args = other._args;
  40. this->_size = other._size;
  41. other._args = nullptr;
  42. other._size = 0;
  43. return *this;
  44. }
  45. int size() const { return _size; }
  46. List to_list() noexcept {
  47. List ret(_size);
  48. for(int i=0; i<_size; i++) ret[i] = _args[i];
  49. return ret;
  50. }
  51. void extend_self(PyObject* self){
  52. PyObject** old_args = _args;
  53. int old_size = _size;
  54. _alloc(old_size+1);
  55. _args[0] = self;
  56. for(int i=0; i<old_size; i++) _args[i+1] = old_args[i];
  57. _pool.dealloc(old_args, old_size);
  58. }
  59. ~Args(){ _pool.dealloc(_args, _size); }
  60. };
  61. inline const Args& no_arg() {
  62. static const Args _zero(0);
  63. return _zero;
  64. }
  65. typedef Args Tuple;
  66. } // namespace pkpy