简体   繁体   English

简单循环缓冲区:需要扩展 function 覆盖旧数据

[英]Simple circular buffer: Need to extend function to overwrite old data

I'm trying to implement an simple Circular Buffer with overwriting old data (Just experimenting with buffers).我正在尝试实现一个简单的循环缓冲区,覆盖旧数据(只是试验缓冲区)。 Actually I implemented a buffer but it is not overwriting the old data.实际上我实现了一个缓冲区,但它没有覆盖旧数据。 When the buffer is full it will not add new data to the array.当缓冲区已满时,它不会向数组添加新数据。

I have the following:我有以下内容:

//Struct with 8 bytes
typedef struct
{
   int8 data_A;                        
   int16 data_B;
   int8 data_C;
   int32 data_D; 
} MyData_Struct_t

//The Circular buffer struct
typedef struct {
   MyData_Struct_t  myData[10]; // 10 elemtns of MyData_Struct_t
   int8 write_idx
   int8 read_idx
   int8 NrOfMessagesinTheQue
} RingBuffer


static MyData_Struct_t  myDataVariable =  {0}; // Instance of MyData_Struct_t
static RingBuffer myRingBuffer= { 0 };      // Instance of myRingBuffer

myDataVariable.data_A = getData(A);  // Lets' say getData() function is called cyclic and new data is received
myDataVariable.data_B = getData(B);  
myDataVariable.data_C = getData(C);   
myDataVariable.data_D = getData(D); 

// Here I call a function to fill the array with data
writeDataToRingbuffer(&myRingBuffer, &myDataVariable); 

void writeDataToRingbuffer(RingBuffer *pBuf, MyData_Struct_t *Data)
{
   if (10 <= pBuf->NrOfMessagesinTheQue)
   {
        // Buffer is Full
   }

   else if (pBuf->write_idx < 10)
   {
      (void)memcpy(&pBuf->myData[pBuf->write_idx], Data, 
sizeof(MyData_Struct_t));  //myData will be read later by another function

      if ((10 - 1u) == pBuf->write_idx)
      {
         pBuf->write_idx = 0u;
      }

      else
      {
         pBuf->write_idx += 1;
      }

      pBuf->NrOfMessagesinTheQue++;
   }

   else
   {
      // Out of boundary
   }
}

I need some ideas how to extend this function in order to overwrite old data?我需要一些想法如何扩展这个 function 以覆盖旧数据?

Would be very thankful!将不胜感激!

If you just want to overwrite the oldest data just use the index modulo the size of the buffer:如果您只想覆盖最旧的数据,只需使用以缓冲区大小为模的索引:

#define BUFFER_SIZE 10  // size of myData

void writeDataToRingbuffer(RingBuffer *pBuf, MyData_Struct_t *Data)
{
    (void)memcpy(&pBuf->myData[pBuf->write_idx % BUFFER_SIZE], Data, 
         sizeof(MyData_Struct_t));  //myData will be read later by another function

    pBuf->write_idx += 1;
    pBuf->NrOfMessagesinTheQue++;
}

With this method you can also combine write_idx and NrOfMessageinTheQue since you never have to reset the index to 0 now.使用此方法,您还可以组合 write_idx 和 NrOfMessageinTheQue,因为您现在不必将索引重置为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM