uhf_buffer.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "uhf_buffer.h"
  2. #include <stdlib.h>
  3. #include <string.h>
  4. Buffer* uhf_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 uhf_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 uhf_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* uhf_buffer_get_data(Buffer* buf) {
  41. return buf->data;
  42. }
  43. size_t uhf_buffer_get_size(Buffer* buf) {
  44. return buf->size;
  45. }
  46. bool uhf_is_buffer_closed(Buffer* buf) {
  47. return buf->closed;
  48. }
  49. void uhf_buffer_close(Buffer* buf) {
  50. buf->closed = true;
  51. }
  52. void uhf_buffer_reset(Buffer* buf) {
  53. for(size_t i = 0; i < MAX_BUFFER_SIZE; i++) {
  54. buf->data[i] = 0;
  55. }
  56. buf->size = 0;
  57. buf->closed = false;
  58. }
  59. void uhf_buffer_free(Buffer* buf) {
  60. free(buf->data);
  61. free(buf);
  62. }