JUCE_FIFO实现分析
JUCE_FIFO代码简单剖析,此处的剖析就是给自己留一个方便查询的内容;不做太多内容的要求,只做简单的记录;本文以初学者的角度来些,大牛请飘过O(∩_∩)O
FIFO的功能在博客的其他帖子里面已经有说明了,这里就简单通过图表说明下类里面的两个函数的实现机制,以及使用方法。下面写贴出代码和例子
1 void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, 2 int& blockSize1, int& startIndex2, int& blockSize2) const noexcept 3 { 4 const int vs = validStart.get(); 5 const int ve = validEnd.value; 6 const int freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve); 7 numToWrite = jmin (numToWrite, freeSpace - 1); 8 if (numToWrite <= 0) 9 { 10 startIndex1 = 0; 11 startIndex2 = 0; 12 blockSize1 = 0; 13 blockSize2 = 0; 14 } 15 else 16 { 17 startIndex1 = ve; 18 startIndex2 = 0; 19 blockSize1 = jmin (bufferSize - ve, numToWrite); 20 numToWrite -= blockSize1; 21 blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, vs); 22 } 23 } 24 25 26 void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, 27 int& startIndex2, int& blockSize2) const noexcept 28 { 29 const int vs = validStart.value; 30 const int ve = validEnd.get(); 31 const int numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve)); 32 numWanted = jmin (numWanted, numReady); 33 if (numWanted <= 0) 34 { 35 startIndex1 = 0; 36 startIndex2 = 0; 37 blockSize1 = 0; 38 blockSize2 = 0; 39 } 40 else 41 { 42 startIndex1 = vs; 43 startIndex2 = 0; 44 blockSize1 = jmin (bufferSize - vs, numWanted); 45 numWanted -= blockSize1; 46 blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, ve); 47 } 48 }
以上是程序具体实现,下面贴出代码例子;
1 e.g. 2 @code 3 class MyFifo 4 { 5 public: 6 MyFifo() : abstractFifo (1024) 7 { 8 } 9 void addToFifo (const int* someData, int numItems) 10 { 11 int start1, size1, start2, size2; 12 abstractFifo.prepareToWrite (numItems, start1, size1, start2, size2); 13 if (size1 > 0) 14 copySomeData (myBuffer + start1, someData, size1); 15 if (size2 > 0) 16 copySomeData (myBuffer + start2, someData + size1, size2); 17 abstractFifo.finishedWrite (size1 + size2); 18 } 19 void readFromFifo (int* someData, int numItems) 20 { 21 int start1, size1, start2, size2; 22 abstractFifo.prepareToRead (numSamples, start1, size1, start2, size2); 23 if (size1 > 0) 24 copySomeData (someData, myBuffer + start1, size1); 25 if (size2 > 0) 26 copySomeData (someData + size1, myBuffer + start2, size2); 27 abstractFifo.finishedRead (size1 + size2); 28 } 29 private: 30 AbstractFifo abstractFifo; 31 int myBuffer [1024]; 32 }; 33 @endcode 34 */
其实在这我不想说的太多,主要是刚开始看代码和我自己的想法不太一致,后来详细看了下其实也很简单,就是一个循环队列的实现;使用开始和技术指针确定写入、读取位置提供给外部使用,外部程序无需再自己处理写入、读取位置的判断。就一下两种可能性,一个是开始位置在前结束位置在后,一个是开始位置在后结束位置在前;