I would like to have a class which supports outputting bits into a file. This is what I came up with but I fear there are many poor decisions. Should I inherit from a std::ofstream
instead of keeping it as a data member?
class OFBitStream final
{
static const std::size_t bitset_size = 8 * sizeof(unsigned long);
std::bitset<bitset_size> bitset;
std::size_t current_bit;
std::ofstream &_stream;
void flush() {
for (auto i = current_bit; i < bitset_size; ++i) {
bitset[i] = false;
}
auto buffer = bitset.to_ulong();
while (buffer != 0) {
_stream.write(reinterpret_cast<char *>(&buffer), 1);
buffer >>= 8;
}
}
public:
OFBitStream(std::ofstream &stream)
: bitset(0), current_bit(0), _stream(stream) {}
~OFBitStream() {
flush();
_stream.close();
}
friend OFBitStream &operator<<(OFBitStream &dst, const bool &data)
{
dst.bitset[dst.current_bit++] = data;
if (dst.current_bit == dst.bitset_size) {
dst.flush();
dst.current_bit = 0;
}
return dst;
}
};