kst/kte/AppendBuffer.cc

59 lines
1.1 KiB
C++

#include <cassert>
#include <iostream>
#include "AppendBuffer.h"
namespace kte {
void
AppendBuffer::Append(const char *s, int slen)
{
char *nc = nullptr;
int sz = this->len + slen;
assert(this->len + slen > this->len);
if (sz >= this->cap) {
std::cerr << "AppendBuffer: resizing from " << this->cap << "b to ";
while (sz > this->cap) {
if (this->cap == 0) {
this->cap = sizeof(uintptr_t);
} else {
this->cap <<= 1;
}
}
std::cerr << this->cap << "bytes.\n";
nc = new char[this->cap];
std::copy_n(this->b, this->len, nc);
delete[] this->b;
this->b = nc;
}
std::copy_n(s, slen, this->b+len);
this->len += slen;
}
void
AppendBuffer::Append(const std::string& s)
{
return this->Append(s.c_str(), static_cast<int>(s.length()));
}
void
AppendBuffer::Append(const char ch)
{
return this->Append(&ch, 1);
}
std::ostream& operator<<(std::ostream &stream, const AppendBuffer buf) {
return stream << "AppendBuffer<" << buf.cap << ", " << buf.len << "> " << buf.b;
}
} // namespace kte