|
本帖最后由 armstrong 于 2018-1-25 20:27 编辑
gy_fifo.hpp
- #ifndef __FIFO_HPP__
- #define __FIFO_HPP__
- #include <stdint.h>
- class GYFIFO
- {
- private:
- uint8_t *buffer;
- uint32_t size;
- uint32_t ip;
- uint32_t op;
- uint32_t (*puter)(GYFIFO& obj, uint8_t const *buf, uint32_t num);
- /* 作为真正操纵FIFO写入功能的函数 */
- static uint32_t RealPut(GYFIFO& obj, uint8_t const *buf, uint32_t num);
- static uint32_t DumyPut(GYFIFO& obj, uint8_t const *buf, uint32_t num);
- public:
- /* 构造器。切勿调用OS函数 */
- GYFIFO(uint8_t *buf, uint32_t sz):
- ip(0), op(0),
- puter(DumyPut)
- {
- buffer = buf;
- size = sz;
- if(buf && sz){
- /* FIFO有效 */
- puter = RealPut;
- }
- }
- /* 析构器 */
- ~GYFIFO()
- {
- puter = DumyPut;
- Clear();
- buffer = NULL;
- size = 0;
- }
- /* 把数据写入FIFO,返回成功写入的字节数 */
- uint32_t Put(uint8_t const *buf, uint32_t num);
- /* 读取FIFO里的数据,返回成功读取的字节数 */
- uint32_t Get(uint8_t *buf, uint32_t sz);
- /* 查看FIFO里现存的数据字节数 */
- uint32_t Count() const
- {
- int num = (int)(ip - op);
- if(num < 0){
- num += size;
- }
- return num;
- }
- /* 查看FIFO当前剩余的空闲空间 */
- uint32_t NumFree() const
- {
- uint32_t num = Count();
- return (size - num - 1);
- }
- /* 查看FIFO缓冲区的原始容量 */
- uint32_t Size() const
- {
- return size;
- }
- /* 清空FIFO */
- void Clear()
- {
- op = ip;
- }
- };
- #endif /* __FIFO_HPP__ */
复制代码
gy_fifo.cpp
- #include "gy_fifo.hpp"
- /* 作为FIFO无效时的空写入函数 */
- uint32_t GYFIFO::DumyPut(GYFIFO& obj, uint8_t const *buf, uint32_t num)
- {
- return num;
- }
- uint32_t GYFIFO::RealPut(GYFIFO& obj, uint8_t const *buf, uint32_t num)
- {
- uint32_t nfree = obj.NumFree();
- uint32_t index = obj.ip;
- uint32_t ncpy;
-
- if(num > nfree){
- num = nfree;
- }
- ncpy = num;
- if(index + ncpy >= obj.size){
- /* 跨越缓存边界,需要分段拷贝 */
- ncpy = obj.size - index;
- memcpy(obj.buffer+index, buf, ncpy);
- buf = buf + ncpy;
- ncpy = num - ncpy;
- index = 0;
- }
- if(ncpy > 0){
- memcpy(obj.buffer+index, buf, ncpy);
- index += ncpy;
- }
-
- obj.ip = index;
- return num;
- }
- uint32_t GYFIFO::Put(uint8_t const *buf, uint32_t num)
- {
- return puter(*this, buf, num);
- }
- uint32_t GYFIFO::Get(uint8_t *buf, uint32_t sz)
- {
- uint32_t ntotal = Count();
- uint32_t index = op;
- uint32_t ncpy;
-
- if(ntotal > sz){
- ntotal = sz;
- }
- ncpy = ntotal;
- if(index + ncpy >= size){
- /* 跨越缓存边界,需要分段拷贝 */
- ncpy = size - index;
- memcpy(buf, buffer+index, ncpy);
- buf = buf + ncpy;
- ncpy = ntotal - ncpy;
- index = 0;
- }
- if(ncpy > 0){
- memcpy(buf, buffer+index, ncpy);
- index += ncpy;
- }
-
- op = index;
- return ntotal;
- }
复制代码
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
阿莫论坛20周年了!感谢大家的支持与爱护!!
月入3000的是反美的。收入3万是亲美的。收入30万是移民美国的。收入300万是取得绿卡后回国,教唆那些3000来反美的!
|