分享一个ringbuffer C程序

2019-12-12 18:10发布

分享一个ringbuffer C程序
ringbuffer.h
  1. #ifndef __RINGBUFFER_H__
  2. #define __RINGBUFFER_H__

  3. #include <stdint.h>

  4. typedef struct RingBuffer_s {
  5.         char * Head;
  6.         char * Tail;
  7.         char * Start;
  8.         char * End;
  9. } RingBuffer_t;

  10. uint8_t rb_Get(RingBuffer_t *rb, char * c);
  11. uint8_t rb_Put(RingBuffer_t *rb, char c);
  12. void    rb_Init(RingBuffer_t *rb, char * buffer, int size);

  13. #endif
复制代码
ringbuffer.c
  1. #include "ring_buffer.h"

  2. uint8_t rb_Put(RingBuffer_t *rb, char c)
  3. {
  4.         char *next = rb->Head + 1;
  5.         if (next == rb->End)
  6.                 next = rb->Start;
  7.         if (next == rb->Tail)
  8.                 return 0;
  9.         *rb->Head = c;
  10.         rb->Head = next;
  11.         return 1;
  12. }

  13. uint8_t rb_Get(RingBuffer_t *rb, char * c)
  14. {
  15.         char *next;
  16.         if (rb->Tail == rb->Head)        // No data in ring
  17.         {
  18.                 *c = 0;
  19.                 return 0;
  20.         }
  21.         *c = *rb->Tail;                                // Get data and move to next
  22.         next = rb->Tail + 1;
  23.         if (next == rb->End)                // Check for ring
  24.                 next = rb->Start;
  25.         rb->Tail = next;
  26.         return 1;
  27. }

  28. void rb_Init(RingBuffer_t *rb, char * buffer, int size)
  29. {
  30.         rb->Tail = rb->Head = rb->Start = buffer;
  31.         rb->End = buffer + size;
  32. }
复制代码
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。