utils_ringbuff.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Tencent is pleased to support the open source community by making IoT Hub
  3. available.
  4. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
  5. * Licensed under the MIT License (the "License"); you may not use this file
  6. except in
  7. * compliance with the License. You may obtain a copy of the License at
  8. * http://opensource.org/licenses/MIT
  9. * Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is
  11. * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  12. KIND,
  13. * either express or implied. See the License for the specific language
  14. governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include "utils_ringbuff.h"
  19. #include <stdio.h>
  20. #include <string.h>
  21. int ring_buff_init(sRingbuff *ring_buff, char *buff, uint32_t size)
  22. {
  23. ring_buff->buffer = buff;
  24. ring_buff->size = size;
  25. ring_buff->readpoint = 0;
  26. ring_buff->writepoint = 0;
  27. memset(ring_buff->buffer, 0, ring_buff->size);
  28. ring_buff->full = false;
  29. return RINGBUFF_OK;
  30. }
  31. int ring_buff_flush(sRingbuff *ring_buff)
  32. {
  33. ring_buff->readpoint = 0;
  34. ring_buff->writepoint = 0;
  35. memset(ring_buff->buffer, 0, ring_buff->size);
  36. ring_buff->full = false;
  37. return RINGBUFF_OK;
  38. }
  39. int ring_buff_push_data(sRingbuff *ring_buff, uint8_t *pData, int len)
  40. {
  41. int i;
  42. if (len > ring_buff->size) {
  43. return RINGBUFF_TOO_SHORT;
  44. }
  45. for (i = 0; i < len; i++) {
  46. if (((ring_buff->writepoint + 1) % ring_buff->size) == ring_buff->readpoint) {
  47. ring_buff->full = true;
  48. return RINGBUFF_FULL;
  49. } else {
  50. if (ring_buff->writepoint < (ring_buff->size - 1)) {
  51. ring_buff->writepoint++;
  52. } else {
  53. ring_buff->writepoint = 0;
  54. }
  55. ring_buff->buffer[ring_buff->writepoint] = pData[i];
  56. }
  57. }
  58. return RINGBUFF_OK;
  59. }
  60. int ring_buff_pop_data(sRingbuff *ring_buff, uint8_t *pData, int len)
  61. {
  62. int i;
  63. if (len > ring_buff->size) {
  64. return RINGBUFF_TOO_SHORT;
  65. }
  66. for (i = 0; i < len; i++) {
  67. if (ring_buff->writepoint == ring_buff->readpoint) {
  68. break;
  69. } else {
  70. if (ring_buff->readpoint == (ring_buff->size - 1)) {
  71. ring_buff->readpoint = 0;
  72. }
  73. else {
  74. ring_buff->readpoint++;
  75. }
  76. pData[i] = ring_buff->buffer[ring_buff->readpoint];
  77. }
  78. }
  79. return i;
  80. }