00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #include <spl/Exception.h>
00018 #include <spl/math/BitMask.h>
00019 #include <memory.h>
00020
00021 BitMask::BitMask(int rows, int cols)
00022 : m_rows(rows), m_cols(cols)
00023 {
00024 m_size = (rows * cols)/8 + 8;
00025 if ( NULL == (m_bits = (byte *)malloc( m_size )) )
00026 {
00027 throw OutOfMemoryException();
00028 }
00029 Clear();
00030 }
00031
00032 BitMask::BitMask(const BitMask& bits)
00033 : m_size(bits.m_size), m_rows(bits.m_rows), m_cols(bits.m_cols)
00034 {
00035 if ( NULL == (m_bits = (byte *)malloc( m_size )) )
00036 {
00037 throw OutOfMemoryException();
00038 }
00039 Clear();
00040
00041 memcpy(m_bits, bits.m_bits, m_size);
00042 }
00043
00044 BitMask::~BitMask()
00045 {
00046 free( m_bits );
00047 }
00048
00049 BitMask& BitMask::operator =(const BitMask& bits)
00050 {
00051 free( m_bits );
00052
00053 m_size = bits.m_size;
00054 m_rows = bits.m_rows;
00055 m_cols = bits.m_cols;
00056
00057 if ( NULL == (m_bits = (byte *)malloc( m_size )) )
00058 {
00059 throw OutOfMemoryException();
00060 }
00061 Clear();
00062
00063 memcpy(m_bits, bits.m_bits, m_size);
00064
00065 return *this;
00066 }
00067
00068 void BitMask::GetByteBit(int row, int col, int *bytenum, int *bytebit)
00069 {
00070 if ( row >= m_rows || row < 0 || col >= m_cols || col < 0 )
00071 {
00072 throw new IndexOutOfBoundsException();
00073 }
00074 int bitnum = row * m_rows + col;
00075 *bytenum = bitnum / 8;
00076 *bytebit = bitnum % 8;
00077 }
00078
00079 void BitMask::Set(int row, int col)
00080 {
00081 int bytenum, bytebit;
00082 GetByteBit(row, col, &bytenum, &bytebit);
00083 m_bits[bytenum] |= 1<<bytebit;
00084 }
00085
00086 bool BitMask::IsSet(int row, int col)
00087 {
00088 int bytenum, bytebit;
00089 GetByteBit(row, col, &bytenum, &bytebit);
00090 return (m_bits[bytenum] & (1<<bytebit)) != 0;
00091 }
00092
00093 void BitMask::Clear(int row, int col)
00094 {
00095 int bytenum, bytebit;
00096 GetByteBit(row, col, &bytenum, &bytebit);
00097 m_bits[bytenum] ^= 1<<bytebit;
00098 }
00099
00100 void BitMask::Clear()
00101 {
00102 memset(m_bits, 0, m_size);
00103 }
00104
00105 #ifdef DEBUG
00106 void BitMask::ValidateMem() const
00107 {
00108 ASSERT_MEM( m_bits, m_rows*m_cols );
00109 }
00110
00111 void BitMask::CheckMem() const
00112 {
00113 DEBUG_NOTE_MEM_ALLOCATION(m_bits);
00114 }
00115 #endif