typeinfo.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "pocketpy/interpreter/typeinfo.h"
  2. #include "pocketpy/common/utils.h"
  3. #define CHUNK_SIZE 128
  4. #define LOG2_CHUNK_SIZE 7
  5. void TypeList__ctor(TypeList* self) {
  6. self->length = 0;
  7. memset(self->chunks, 0, sizeof(self->chunks));
  8. }
  9. void TypeList__dtor(TypeList* self) {
  10. for(py_Type t = 0; t < self->length; t++) {
  11. py_TypeInfo* info = TypeList__get(self, t);
  12. (void)info;
  13. }
  14. for(int i = 0; i < PK_MAX_CHUNK_LENGTH; i++) {
  15. if(self->chunks[i]) PK_FREE(self->chunks[i]);
  16. }
  17. }
  18. py_TypeInfo* TypeList__get(TypeList* self, py_Type index) {
  19. assert(index < self->length);
  20. int chunk = index >> LOG2_CHUNK_SIZE;
  21. int offset = index & (CHUNK_SIZE - 1);
  22. return self->chunks[chunk] + offset;
  23. }
  24. py_TypeInfo* TypeList__emplace(TypeList* self) {
  25. int chunk = self->length >> LOG2_CHUNK_SIZE;
  26. int offset = self->length & (CHUNK_SIZE - 1);
  27. if(self->chunks[chunk] == NULL) {
  28. if(chunk >= PK_MAX_CHUNK_LENGTH) {
  29. c11__abort("TypeList__emplace(): max chunk length exceeded");
  30. }
  31. self->chunks[chunk] = PK_MALLOC(sizeof(py_TypeInfo) * CHUNK_SIZE);
  32. memset(self->chunks[chunk], 0, sizeof(py_TypeInfo) * CHUNK_SIZE);
  33. }
  34. self->length++;
  35. return self->chunks[chunk] + offset;
  36. }
  37. void TypeList__apply(TypeList* self, void (*f)(py_TypeInfo*, void*), void* ctx) {
  38. for(int i = 0; i < self->length; i++) {
  39. py_TypeInfo* info = TypeList__get(self, i);
  40. f(info, ctx);
  41. }
  42. }
  43. #undef CHUNK_SIZE
  44. #undef LOG2_CHUNK_SIZE