#include "Defines.h"
#include "BitMask.h"
#include <cstring>
USING_NAMESPACE_LERC
BitMask::BitMask(const BitMask& src) : m_pBits(nullptr), m_nCols(0), m_nRows(0)
{
SetSize(src.m_nCols, src.m_nRows);
if (m_pBits && src.m_pBits)
memcpy(m_pBits, src.m_pBits, Size());
}
BitMask& BitMask::operator= (const BitMask& src)
{
if (this == &src) return *this;
SetSize(src.m_nCols, src.m_nRows);
if (m_pBits && src.m_pBits)
memcpy(m_pBits, src.m_pBits, Size());
return *this;
}
void BitMask::SetAllValid() const
{
memset(m_pBits, 255, Size());
}
void BitMask::SetAllInvalid() const
{
memset(m_pBits, 0, Size());
}
bool BitMask::SetSize(int nCols, int nRows)
{
if (nCols <= 0 || nRows <= 0)
{
Clear();
return (nCols == 0 && nRows == 0);
}
if (nCols != m_nCols || nRows != m_nRows)
{
Clear();
try
{
size_t nPix = (size_t)nCols * (size_t)nRows;
m_pBits = new Byte[(nPix + 7) >> 3];
}
catch (...)
{
return false;
}
if (!m_pBits)
return false;
m_nCols = nCols;
m_nRows = nRows;
}
return m_pBits != nullptr;
}
int BitMask::CountValidBits() const
{
const Byte numBitsHB[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
const Byte* ptr = m_pBits;
int sum = 0;
int i = Size();
while (i--)
{
sum += numBitsHB[*ptr & 15] + numBitsHB[*ptr >> 4];
ptr++;
}
for (int k = m_nCols * m_nRows; k < Size() * 8; k++)
if (IsValid(k))
sum--;
return sum;
}
void BitMask::Clear()
{
delete[] m_pBits;
m_pBits = nullptr;
m_nCols = 0;
m_nRows = 0;
}