vector.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #pragma once
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include "pocketpy/common/algorithm.h"
  5. #ifdef __cplusplus
  6. extern "C" {
  7. #endif
  8. typedef struct c11_array{
  9. void* data;
  10. int count;
  11. int elem_size;
  12. } c11_array;
  13. void c11_array__ctor(c11_array* self, int elem_size, int count);
  14. void c11_array__dtor(c11_array* self);
  15. c11_array c11_array__copy(const c11_array* self);
  16. void* c11_array__at(c11_array* self, int index);
  17. typedef struct c11_vector{
  18. void* data;
  19. int count;
  20. int capacity;
  21. int elem_size;
  22. } c11_vector;
  23. void c11_vector__ctor(c11_vector* self, int elem_size);
  24. void c11_vector__dtor(c11_vector* self);
  25. c11_vector c11_vector__copy(const c11_vector* self);
  26. void* c11_vector__at(c11_vector* self, int index);
  27. void c11_vector__reserve(c11_vector* self, int capacity);
  28. void c11_vector__clear(c11_vector* self);
  29. #define c11__getitem(T, self, index) ((T*)(self)->data)[index]
  30. #define c11__setitem(T, self, index, value) ((T*)(self)->data)[index] = value;
  31. #define c11_vector__push(T, self, elem) \
  32. do{ \
  33. if((self)->count == (self)->capacity) c11_vector__reserve((self), (self)->capacity*2); \
  34. ((T*)(self)->data)[(self)->count] = (elem); \
  35. (self)->count++; \
  36. }while(0)
  37. #define c11_vector__pop(T, self) \
  38. do{ \
  39. (self)->count--; \
  40. }while(0)
  41. #define c11_vector__extend(T, self, p, size) \
  42. do{ \
  43. c11_vector__reserve((self), (self)->count + (size)); \
  44. memcpy((T*)(self)->data + (self)->count, (p), (size) * sizeof(T)); \
  45. (self)->count += (size); \
  46. }while(0)
  47. #define c11_vector__insert(T, self, p, elem) \
  48. do{ \
  49. if((self)->count == (self)->capacity) c11_vector__reserve((self), (self)->capacity*2); \
  50. int __n = (self)->count - (p - (T*)(self)->data); \
  51. memmove(p + 1, p, __n * sizeof(T)); \
  52. *p = (elem); \
  53. (self)->count++; \
  54. }while(0)
  55. #define c11_vector__erase(T, self, p) \
  56. do{ \
  57. int __n = (self)->count - (p - (T*)(self)->data) - 1; \
  58. memmove(p, p + 1, __n * sizeof(T)); \
  59. (self)->count--; \
  60. }while(0)
  61. #define c11_vector__reverse(T, self, start, end) \
  62. do{ \
  63. T* p = (T*)(self)->data + (start); \
  64. T* q = (T*)(self)->data + (end); \
  65. while(p < q){ \
  66. T tmp = *p; *p = *q; *q = tmp; \
  67. p++; q--; \
  68. } \
  69. }while(0)
  70. #ifdef __cplusplus
  71. }
  72. #endif