C语言实现队循FIFO缓冲区-《30天自制操作系统》

本代码整理自《30天自制操作系统》P135的整理FIFO缓冲区

写的很好,所以记录一下(增加了一个fifo8_free函数,用于查询剩余容量,觉得有用)。作者实现的是char类型的缓冲区,但是可以用你要传的任意结构体来替换~~~

fifo8.h

[html]  view plain  copy
  1. /*溢出标志:0-正常,-1-溢出*/  
  2. #define FLAGS_OVERRUN 0x0001  
  3. /*  
  4.         buf- 缓冲区地址  
  5.         size- 大小  
  6.         free- 空余容量  
  7.         putP- 下一个数据写入位置  
  8.         getP- 下一个数据独处位置  
  9. */  
  10. struct FIFO8{  
  11.          unsigned char *buf;  
  12.          int putP,getP,size,free,flags;  
  13. };  
  14.   
  15. void fifo8_init(struct FIFO8 *fifo,int size, unsigned char *buf);  
  16. int fifo8_put(struct FIFO8 *fifo,unsigned char data);  
  17. int fifo8_get(struct FIFO8 *fifo);  
  18. int fifo8_status(struct FIFO8 *fifo);  
  19. int fifo8_free(struct FIFO7 *fifo);  
fifo8.c
[html]  view plain  copy
  1. #include "fifo8.h"  
  2. void fifo8_init(struct FIFO8 *fifo,int size, unsigned char *buf)  
  3. /*初始化*/  
  4. {  
  5.         fifo->buf=buf;  
  6.         fifo->flags=0;            
  7.         fifo->free=size;  
  8.         fifo->size=size;  
  9.         fifo->putP=0;                     
  10.         fifo->getP=0;                     
  11.   
  12.          return;  
  13. }  
  14. int fifo8_putPut(struct FIFO8 *fifo,unsigned char data)  
  15. /*向FIFO 中写入数据 */  
  16. {  
  17.          if(fifo->free==0){  
  18.                 fifo->flags |= FLAGS_OVERRUN;  
  19.                  return -1;  
  20.         }  
  21.         fifo->buf[fifo->putP] = data;  
  22.         fifo->putP++;  
  23.          //循环队列缓冲区  
  24.          if(fifo->putP == fifo->size){  
  25.                 fifo->putP = 0;  
  26.         }  
  27.         fifo->free--;  
  28.   
  29.          return 0;  
  30. }  
  31. int fifo8_get(struct FIFO8 *fifo)  
  32. /*从FIFO 中取出一个数据 */  
  33. {  
  34.          int data;  
  35.          if(fifo->free == fifo->size){  
  36.                  return -1;  
  37.         }  
  38.         data = fifo->getP;  
  39.         fifo->getP++;  
  40.          if(fifo->getP == fifo->size){//用来实现循环  
  41.                 fifo->getP = 0;  
  42.         }  
  43.         fifo->free++;  
  44.           
  45.          return data;  
  46. }  
  47. int fifo8_status(struct FIFO8 *fifo)  
  48. /*缓冲区被使用容量*/  
  49. {  
  50.          return fifo->size-fifo->free;  
  51. }  
  52. int fifo8_free(struct FIFO8 *fifo)  
  53. /*缓冲区剩余容量*/  
  54. {  
  55.          return fifo->free;  
  56. }  

http://blog.csdn.net/fovwin/article/details/8129102
学习的地方:返回值为void时可以return;循环缓冲区的构造;溢出标志设定;

你可能感兴趣的:(ffmpeg)