uhf_buffer.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "uhf_buffer.h"
  2. #include <stdlib.h>
  3. #include <string.h>
  4. Buffer* buffer_alloc(size_t initial_capacity) {
  5. Buffer* buf = (Buffer*)malloc(sizeof(Buffer));
  6. buf->data = (uint8_t*)malloc(sizeof(uint8_t) * initial_capacity);
  7. if(!buf->data) {
  8. free(buf);
  9. return NULL;
  10. }
  11. buf->size = 0;
  12. buf->capacity = initial_capacity;
  13. return buf;
  14. }
  15. bool buffer_append_single(Buffer* buf, uint8_t data) {
  16. if(buf->closed) return false;
  17. if(buf->size + 1 > buf->capacity) {
  18. size_t new_capacity = buf->capacity * 2;
  19. uint8_t* new_data = (uint8_t*)realloc(buf->data, sizeof(uint8_t) * new_capacity);
  20. if(!new_data) return false;
  21. buf->data = new_data;
  22. buf->capacity = new_capacity;
  23. }
  24. buf->data[buf->size++] = data;
  25. return true;
  26. }
  27. bool buffer_append(Buffer* buf, uint8_t* data, size_t data_size) {
  28. if(buf->closed) return false;
  29. if(buf->size + data_size > buf->capacity) {
  30. size_t new_capacity = buf->capacity * 2;
  31. uint8_t* new_data = (uint8_t*)realloc(buf->data, new_capacity);
  32. if(!new_data) return false;
  33. buf->data = new_data;
  34. buf->capacity = new_capacity;
  35. }
  36. memcpy((void*)&buf->data[buf->size], data, data_size);
  37. buf->size += data_size;
  38. return true;
  39. }
  40. uint8_t* buffer_get_data(Buffer* buf) {
  41. return buf->data;
  42. }
  43. size_t buffer_get_size(Buffer* buf) {
  44. return buf->size;
  45. }
  46. void buffer_close(Buffer* buf) {
  47. buf->closed = true;
  48. }
  49. void buffer_reset(Buffer* buf) {
  50. for(size_t i = 0; i < MAX_BUFFER_SIZE; i++) {
  51. buf->data[i] = 0;
  52. }
  53. buf->size = 0;
  54. buf->closed = false;
  55. }
  56. void buffer_free(Buffer* buf) {
  57. free(buf->data);
  58. free(buf);
  59. }