#include <stdint.h>
#include <cassert>
#include <iostream>
#include <string>
#include <algorithm>
#define SAFE_FREE(x) do { if ((x) != nullptr) { free((x)); (x) = nullptr;} } while (0)
class out_stream {
public:
out_stream() {
data_ = nullptr;
size_ = 0;
capacity_ = 0;
}
out_stream(const out_stream &) = delete;
out_stream & operator = (const out_stream &) = delete;
virtual ~out_stream() {
SAFE_FREE(data_);
size_ = 0;
capacity_ = 0;
}
public:
void write(const char *input, size_t len) {
int remain = capacity_ - size_;
if (remain < len) {
enlarge(size_ + len);
}
std::copy(input, input + len, data_ + size_);
size_ += len;
}
void read(std::string &str) {
str.assign((char *)data_, size_);
}
private:
void enlarge(int new_size) {
if (new_size <= capacity_) {
return;
}
uint8_t *new_data = nullptr;
if (data_ != nullptr) {
new_size = std::max(capacity_ << 1, new_size);
new_data = (uint8_t *)malloc(sizeof(uint8_t) * new_size);
assert(new_data != nullptr);
std::copy(data_, data_ + size_, new_data);
SAFE_FREE(data_);
}
else {
new_size += 32;
new_data = (uint8_t *)malloc(sizeof(uint8_t) * new_size);
}
data_ = new_data;
capacity_ = new_size;
}
private:
uint8_t *data_;
int size_;
int capacity_;
};
int main() {
out_stream stream;
stream.write("AAAA", 4);
std::string str;
stream.read(str);
std::cout << str << std::endl;
return 0;
}