a cpp buffer implementation.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define BUF_DEFAULT_CAPACITY 20
#define ALLOC_BYTES(amnt) static_cast<unsigned char*>(std::malloc(amnt))
class Buf {
public:
Buf(): _cap(BUF_DEFAULT_CAPACITY),
_len(0),
_data(ALLOC_BYTES(_cap))
{}
~Buf()
{
std::free((void*)_data);
}
size_t getSpace() const { return _cap - _len; }
unsigned char& operator[](size_t index)
{
return _data[index];
}
void put(unsigned char uch)
{
if(!getSpace())
expand(30);
_data[_len++] = uch;
}
template<class T>
void put(const T& value)
{
if(getSpace() <= sizeof(T))
expand(50 + sizeof(T));
const unsigned char* reader = reinterpret_cast<const unsigned char*>(&value);
const unsigned char* end = reader + sizeof(T);
while(reader != end) {
_data[_len++] = *reader++;
}
}
template<class T>
Buf& operator<<(const T& value)
{
put(value);
return *this;
}
private:
void expand(size_t amount)
{
_cap += amount;
_data = static_cast<unsigned char*>(std::realloc((void*)_data, _cap));
}
private:
size_t _cap;
size_t _len;
unsigned char* _data;
};
int main(int agrc, char const* argv[])
{
Buf buf;
buf.put(7);
buf << 6 << 8 << 4 << 99 << 33 << 22 << 77;
std::printf("space is %lu\n", buf.getSpace());
return 0;
}