buffer.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #include "tunnel.h"
  2. #include "buffer.h"
  3. #include <assert.h>
  4. struct ring_buffer*
  5. alloc_ring_buffer(int len) {
  6. struct ring_buffer* rb = (struct ring_buffer*)malloc(sizeof(*rb));
  7. memset(rb, 0, sizeof(*rb));
  8. rb->data_ptr = (char *)malloc(len);
  9. rb->max_len = len;
  10. return rb;
  11. }
  12. void
  13. free_ring_buffer(struct ring_buffer* rb) {
  14. free(rb->data_ptr);
  15. free(rb);
  16. }
  17. char*
  18. get_ring_buffer_write_ptr(struct ring_buffer* rb, int* max_len) {
  19. int read_pos = rb->read_pos;
  20. if (rb->write_pos < read_pos) {
  21. read_pos -= 2 * rb->max_len;
  22. }
  23. assert(rb->write_pos >= read_pos);
  24. if (rb->write_pos - read_pos == rb->max_len) {
  25. return NULL;
  26. }
  27. int w_idx = rb->write_pos % rb->max_len;
  28. int r_idx = read_pos % rb->max_len;
  29. if (w_idx >= r_idx) {
  30. *max_len = rb->max_len - w_idx;
  31. }else {
  32. *max_len = r_idx - w_idx;
  33. }
  34. return rb->data_ptr + w_idx;
  35. }
  36. void
  37. move_ring_buffer_write_pos(struct ring_buffer*rb, int len) {
  38. int tmp = rb->write_pos + len;
  39. if (tmp > 3 * rb->max_len && rb->write_pos > rb->read_pos) {
  40. tmp -= 2 * rb->max_len;
  41. }
  42. rb->write_pos = tmp;
  43. }
  44. char*
  45. get_ring_buffer_read_ptr(struct ring_buffer* rb, int* read_len) {
  46. int write_pos = rb->write_pos;
  47. int read_pos = rb->read_pos;
  48. if (write_pos < read_pos) {
  49. read_pos -= 2 * rb->max_len;
  50. }
  51. assert(write_pos >= read_pos);
  52. if (read_pos == write_pos) {
  53. return NULL;
  54. }
  55. int w_idx = write_pos % rb->max_len;
  56. int r_idx = read_pos % rb->max_len;
  57. if (w_idx > r_idx) {
  58. *read_len = w_idx - r_idx;
  59. }else {
  60. *read_len = rb->max_len - r_idx;
  61. }
  62. return rb->data_ptr + read_pos % rb->max_len;
  63. }
  64. void
  65. move_ring_buffer_read_pos(struct ring_buffer*rb, int len) {
  66. // int read_pos = rb->read_pos;
  67. // if (rb->write_pos < read_pos) {
  68. // read_pos -= 2 * rb->max_len;
  69. // }
  70. rb->read_pos += len;
  71. }
  72. int
  73. is_ring_buffer_empty(struct ring_buffer* rb) {
  74. int write_pos = rb->write_pos;
  75. int read_pos = rb->read_pos;
  76. if (write_pos < read_pos) {
  77. read_pos -= 2 * rb->max_len;
  78. }
  79. assert(write_pos >= read_pos);
  80. if (read_pos == write_pos) {
  81. return 1;
  82. }
  83. return 0;
  84. }
  85. void
  86. reset_ring_buffer(struct ring_buffer* rb) {
  87. rb->read_pos = 0;
  88. rb->write_pos = 0;
  89. }