自定義stringbuffer類
#include<iostream>
#include <stdarg.h>
#include<string.h>
#include<vector>
class tool_strbuf
{
public:
tool_strbuf():tool_strbuf(0)
{}
tool_strbuf(uint32_t capacity):_len(0)
{
_capacity=capacity;
if(_capacity<256)
{
_capacity=256;
}
_buf=new char[_capacity]{0};
}
void format(const char*fmt,...)
{
clear();
va_list args;
va_start(args, fmt);
int n=vsprintf(_buf + _len,fmt, args);
_len += n;
va_end(args);
}
void append_format(const char*fmt,...)
{
va_list args;
va_start(args, fmt);
int n=vsprintf(_buf + _len,fmt, args);
_len += n;
va_end(args);
}
///轉為16進位制字串
void to16str(const std::vector<char>& arr)
{
if(arr.size())
{
to16str( &arr[0], arr.size());
}
else
{
to16str(nullptr, 0);
}
}
///轉為16進位制字串
void to16str(const char* data, uint32_t len)
{
clear();
if(len<1)
{
return;
}
_len = len*3 - 1 ;
reserve(_len + 1);
sprintf(_buf, "%02X", static_cast<unsigned char>(*data++));
char* tmp = _buf+2;
for(uint32_t i=1; i<len; i++)
{
sprintf(tmp, " %02X", static_cast<unsigned char>(*data++));
tmp+=3;
}
*tmp=0;
}
tool_strbuf& append(const std::string& str)
{
return append(str.c_str(), str.length());
}
tool_strbuf& append(const char* str)
{
auto len = static_cast<uint32_t>(strlen(str));
return append(str, len);
}
tool_strbuf& append(const char* str, uint32_t n)
{
auto len = n+1;
reserve(_len+len);
strcpy(_buf+_len, str);
_len+=len-1;
return *this;
}
void reserve(uint32_t capacity)
{
if(capacity > _capacity)
{
_capacity = 2*_len > capacity ? 2*_len:capacity;
auto tmp = new char[_capacity];
strcpy(tmp, _buf);
delete [] _buf;
_buf=tmp;
}
}
const char* c_str()const
{
return _buf;
}
void clear()
{
_len=0;
*_buf=0;
}
uint32_t len() const
{
return _len;
}
uint32_t capacity()const
{
return _capacity;
}
tool_strbuf(const tool_strbuf&)=delete;
tool_strbuf& operator=(const tool_strbuf&)=delete;
~tool_strbuf()
{
delete [] _buf;
}
private:
uint32_t _len;
uint32_t _capacity;
char* _buf;
};
int main()
{
tool_strbuf str;
str.format("%s", "hhh");
std::cout<<str.c_str()<<std::endl;
str.append_format("g%d,%s", 3,"rt ");
std::cout<<str.c_str()<<std::endl;
return 0;
}
hhh
hhhg3,rt