vector.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "pocketpy/common/vector.h"
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "pocketpy/common/utils.h"
  5. #include "pocketpy/config.h"
  6. void c11_vector__ctor(c11_vector* self, int elem_size) {
  7. self->data = NULL;
  8. self->length = 0;
  9. self->capacity = 0;
  10. self->elem_size = elem_size;
  11. }
  12. void c11_vector__dtor(c11_vector* self) {
  13. if(self->data) PK_FREE(self->data);
  14. self->data = NULL;
  15. self->length = 0;
  16. self->capacity = 0;
  17. }
  18. c11_vector c11_vector__copy(const c11_vector* self) {
  19. c11_vector retval;
  20. c11_vector__ctor(&retval, self->elem_size);
  21. c11_vector__reserve(&retval, self->capacity);
  22. memcpy(retval.data, self->data, (size_t)self->elem_size * (size_t)self->length);
  23. retval.length = self->length;
  24. return retval;
  25. }
  26. void c11_vector__reserve(c11_vector* self, int capacity) {
  27. if(capacity < 4) capacity = 4;
  28. if(capacity <= self->capacity) return;
  29. // self->elem_size * capacity may overflow
  30. self->data = PK_REALLOC(self->data, (size_t)self->elem_size * (size_t)capacity);
  31. if(self->data == NULL) c11__abort("c11_vector__reserve(): out of memory");
  32. self->capacity = capacity;
  33. }
  34. void c11_vector__clear(c11_vector* self) { self->length = 0; }
  35. void* c11_vector__emplace(c11_vector* self) {
  36. if(self->length == self->capacity) c11_vector__reserve(self, self->capacity * 2);
  37. void* p = (char*)self->data + (size_t)self->elem_size * (size_t)self->length;
  38. self->length++;
  39. return p;
  40. }
  41. bool c11_vector__contains(const c11_vector* self, void* elem) {
  42. for(int i = 0; i < self->length; i++) {
  43. void* p = (char*)self->data + (size_t)self->elem_size * (size_t)i;
  44. if(memcmp(p, elem, self->elem_size) == 0) return true;
  45. }
  46. return false;
  47. }
  48. void* c11_vector__submit(c11_vector* self, int* length) {
  49. void* retval = self->data;
  50. *length = self->length;
  51. self->data = NULL;
  52. self->length = 0;
  53. self->capacity = 0;
  54. return retval;
  55. }
  56. void c11_vector__swap(c11_vector *self, c11_vector *other){
  57. c11_vector tmp = *self;
  58. *self = *other;
  59. *other = tmp;
  60. }