// Bit input/output.

#include <iostream>

#include "bitio.h"


void 
bit_packer::write(std::ostream & o, const std::basic_string<bool> & s)
{
  int sz = s.size();
  for (int i=0; i < sz; ++i)
  {
    byte += (s[i] ? 1 : 0);
    if (++count == 8)
    {
      o.put(byte);
      byte = 0;
      count = 0;
    }
    else
      byte <<= 1;
  }
}


void 
bit_packer::flush(std::ostream & o) 
{ 
  if (count)
    o.put(byte << (7 - count)); 
}


bool 
bit_unpacker::read(std::istream & in)
{
  if (count == 0)
  {
    in.get(byte);
    count = 8;
  }
  bool bit = (byte & 0x80);
  --count;
  byte <<= 1;
  return bit;
}
