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

📄 autobuf.h

📁 实时监控
💻 H
字号:
/*
 *	Purpose:	Auto buffer allocation
 *	Module:		General
 *	Usage:		include this file
 *	Author:		nodman
 *	Copyright:	(C)2003 Senao Corp., Shenzhen
 *	History:	2003-6-11 created
 */
#ifndef _AUTO_BUF_H
#define _AUTO_BUF_H

#ifndef byte
typedef unsigned char byte;
#endif

template<typename T> inline
void safe_free(T*& t)
{
	delete[] t;
	t = NULL;
}

// t must be NULL before calling this function!!!
template<typename T> inline
bool safe_alloc(T*& t, int size)
{
	//safe_free(t);
	if( size == 0 )		// new X [0] is illegal!!!
		size = 1;
	t = new T [size];
	return t != NULL;
}

//////////////////////////////////////////////////////////////////////////
// template class autobuf
template<typename T>
class autobuf
{
	T* x;		// buffer
	int s;	// buffer size
public:
	autobuf():x(NULL){}
	autobuf(int size):x(NULL){alloc(size);}
	autobuf(const autobuf<T>& ab){*this = ab;}
	~autobuf(){free();}

	// allocate & free
	bool alloc(int size)
	{
		free();
		s = size;
		return safe_alloc(x, size);
	}
	void free(){safe_free(x); s = 0;}

	// access
	inline T* data() {return x;}
	inline operator T*() {return data();}
	T& operator[](int index) const {return x[index];}

	inline int size() const {return s;}

	// copy & assign
	autobuf<T>& operator=(const autobuf<T>& ab)
	{
		copy_from(ab, ab.size());
		return *this;
	}
	autobuf<T>& operator+=(const autobuf<T>& ab)
	{
		add_from(ab, ab.size());
		return *this;
	}
	autobuf<T> operator +(const autobuf<T>& ab)
	{
		autobuf<T> ret(*this);
		ret += ab;
		return ret;
	}
	bool copy_from(const T* buf, int size)
	{
		if( !buf || size == 0 )
			return false;
		
		if( !alloc(size) )	// alloc() automatically frees
			return false;

		memcpy(x, buf, sizeof(T)*size);

		return true;
	}
	bool add_from(const T* buf, int size)
	{
		if( !buf || size == 0 )
			return false;

		autobuf<T> ret;
		if( !ret.alloc(size()+size) )
			return;

		memcpy(ret, x, sizeof(T)*size());				// copy this
		memcpy((T*)ret+size(), buf, sizeof(T)*size);	// add buf
		*this = ret;

		return true;
	}
};

typedef autobuf<byte> bytebuf;
typedef autobuf<char> charbuf;
typedef autobuf<double> doublebuf;
#endif	// _AUTO_BUF_H

⌨️ 快捷键说明

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