Skip to content

Instantly share code, notes, and snippets.

@rightfold

rightfold/.hpp Secret

Created September 8, 2015 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rightfold/f076a009ec97e46e93b9 to your computer and use it in GitHub Desktop.
Save rightfold/f076a009ec97e46e93b9 to your computer and use it in GitHub Desktop.
#pragma once
#include <algorithm>
#include <iterator>
#include <utility>
#include <vector>
namespace {
template<typename Writer>
class buffered_writer {
public:
buffered_writer(Writer writer, std::size_t size)
: writer(std::move(writer)) {
buffer.reserve(size);
}
~buffered_writer() {
flush();
}
char const* write(char const* begin, char const* end) {
auto n = static_cast<std::size_t>(end - begin);
if (n > buffer.capacity()) {
flush();
return writer.write(begin, end);
} else {
auto to_buffer = std::min(n, buffer.capacity() - buffer.size());
std::copy(begin, begin + to_buffer, std::back_inserter(buffer));
return begin + to_buffer;
}
}
void flush() {
if (!buffer.empty()) {
writer.write(buffer.data(), buffer.data() + buffer.size());
buffer.clear();
}
}
private:
Writer writer;
std::vector<char> buffer;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment