⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cirbuf.h

📁 模仿wiondws写的linux/freeBSD系统的IOCP
💻 H
字号:
#ifndef _CIRBUF_H
#define _CIRBUF_H



template <unsigned int max = 4096>
class cirbuf
{
public:

	cirbuf():r_index(0),w_index(0)
	,r_size(0),w_size(max){}


	/*查看缓冲中的数据但不更改缓冲的状态*/
	unsigned int fetch(char *buffer,unsigned int size)
	{
		if(r_size == 0 || size == 0 || size == 0)
			return 0;
		
		
		char *cur = buffer;
		unsigned int ret = 0;
		unsigned int tmp_size;

		//设置实际的存放字节数量
		size > r_size ? size = r_size : size;

		unsigned int t_r_index = r_index;
		unsigned int t_w_index = w_index;
		while(size > 0)
		{
			
			if(t_r_index >= t_w_index)
			{
				tmp_size = size > max-t_r_index ? max-t_r_index : size;
			}
			else
			{
				tmp_size = size > t_w_index - t_r_index ? t_w_index-t_r_index : size;
			}
			
			memcpy(cur,&buf[t_r_index],tmp_size);
			size -= tmp_size;
			t_r_index = (t_r_index+tmp_size)%max;
			cur += tmp_size;
			ret += tmp_size;
		}

		return ret;

	}


	/*将数据保存进缓冲中*/
	unsigned int put(const char *buffer,unsigned int size)
	{
		if(w_size == 0 || size == 0 || buffer == 0)
			return 0;

		const char *cur = buffer;
		unsigned int ret = 0;
		unsigned int tmp_size;

		//设置实际的存放字节数量
		size > w_size ? size = w_size : size;

		while(size > 0)
		{
			if(w_index >= r_index)
			{
				tmp_size = size > max-w_index ? max-w_index : size;
			}
			else
			{
				tmp_size = size > r_index - w_index ? r_index - w_index : size;
			}

			memcpy(&buf[w_index],cur,tmp_size);
			size -= tmp_size;
			w_size -= tmp_size;
			r_size += tmp_size;
			w_index = (w_index + tmp_size)%max;
			cur += tmp_size;
			ret += tmp_size;
		}

		return ret;

	}

    /*从缓冲中提取数据*/
	int get(char *buffer,unsigned int size)
	{
		if(r_size == 0 || size == 0 || buffer == 0)
			return 0;

		char *cur = buffer;
		unsigned int ret = 0;
		unsigned int tmp_size;

		//设置实际的存放字节数量
		size > r_size ? size = r_size : size;
		while(size > 0)
		{
			
			if(r_index >= w_index)
			{
				tmp_size = size > max-r_index ? max-r_index : size;
			}
			else
			{
				tmp_size = size > w_index - r_index ? w_index-r_index : size;
			}
			memcpy(cur,&buf[r_index],tmp_size);
			size -= tmp_size;
			r_size -= tmp_size;
			w_size += tmp_size;
			r_index = (r_index+tmp_size)%max;
			cur += tmp_size;
			ret += tmp_size;
		}

		return ret;

	}

	inline unsigned int getrsize() const
	{
		return r_size;
	}

	inline unsigned int getwsize() const
	{
		return w_size;
	}


private:
	unsigned int r_index;
	unsigned int w_index;
	unsigned int r_size;
	unsigned int w_size;
	char buf[max];
};



#endif

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -