view BitArray.hpp @ 66:a60c26e34d1a

Avoid apprent hang in beginning, now application shows, but appears frosen. Need better fix.
author Tom Fredrik Blenning Klaussen <bfg@bfgconsult.no>
date Sun, 23 Dec 2012 22:07:57 +0100
parents f339499ecd79
children 9161e9fd5b3f
line wrap: on
line source

#ifndef BITARRAY_HPP
#define BITARRAY_HPP

#include <ostream>

//We should remove these defines from the header, but we keep them for
//now until we have stabilized the API and removed any bugs.
#define HIGH(B) ((B) >> 3)
#define LOW(B) ((B) & 0x07)
#define MASK(X) (0x1 << (7 - X))
#define SELECTMASK(X) (uchar(MASK(X)))
#define DESELECTMASK(X) (uchar(~MASK(X)))
#define NUMCHARS(X) HIGH(X + 7)

#include <cassert>

class QBitArray;
class BitArray
{
  typedef unsigned char uchar;
  typedef unsigned int uint;
  uint size_;
  unsigned char* bits;

public:
  BitArray(uint size, bool val) : size_(size), bits(new uchar[NUMCHARS(size)])
  {
    uint n = NUMCHARS(size);
    for (uint i = 0; i < n; ++i) {
      bits[i] = (val) ? 0xff : 0;
    }
  }

  BitArray(uint size) : size_(size), bits(new uchar[NUMCHARS(size)])
  {
    //We need to initialize the bits beyond size, since they are
    //implicitly used in certain functions.
    bits[NUMCHARS(size) - 1] = 0;
  }

  BitArray() : size_(0), bits(0)
  {
  }

  BitArray(const BitArray& );

  ~BitArray();
  bool testBit(uint i) const
  {
    assert(i < size_);
    return bits[HIGH(i)] & MASK(LOW(i));
  }

  void setBit(uint i, bool val)
  {
    assert(i < size_);
    if (val) {
      bits[HIGH(i)] |= SELECTMASK(LOW(i));
    }
    else {
      bits[HIGH(i)] &= DESELECTMASK(LOW(i));
    }
  }

  uint size() const
  {
    return size_;
  }

  uchar getPaddedChar(size_t offset = 0) const
  {
    assert(size_ > 0);
    assert(HIGH(offset) < NUMCHARS(size_));
    if (LOW(offset) == 0)
      return bits[HIGH(offset)];

    uchar next = ((HIGH(offset) + 1) < NUMCHARS(size_)) ?
      bits[HIGH(offset) + 1]  : 0;
    return ((bits[HIGH(offset)] << 8) | next) >> (8 - LOW(offset));
  }


  bool operator==(const BitArray& rhs) const;
  BitArray& operator=(const BitArray& rhs);
};

std::ostream& operator<<(std::ostream& out, const BitArray& rhs);

#endif //BITARRAY_HPP