1
Fork 0
turbonss/cxxmph/mph_bits.h

68 lines
1.8 KiB
C
Raw Normal View History

#ifndef __CXXMPH_MPH_BITS_H__
#define __CXXMPH_MPH_BITS_H__
#include <stdint.h> // for uint32_t and friends
2012-03-14 21:43:38 +02:00
#include <cassert>
#include <climits>
2012-03-14 23:26:26 +02:00
#include <cmath>
2012-03-14 21:43:38 +02:00
#include <cstdio>
#include <cstring>
#include <limits>
#include <vector>
namespace cxxmph {
2012-03-14 21:43:38 +02:00
class dynamic_2bitset {
public:
2012-03-14 23:26:26 +02:00
dynamic_2bitset() : fill_(false) {}
dynamic_2bitset(uint32_t size, bool fill = false)
: size_(size), fill_(fill), data_(ceil(size / 4.0), ones()*fill) {
2012-03-14 21:43:38 +02:00
}
const uint8_t operator[](uint32_t i) const { return get(i); }
uint8_t get(uint32_t i) const {
return (data_[(i >> 2)] >> (((i & 3) << 1)) & 3);
}
uint8_t set(uint32_t i, uint8_t v) {
2012-03-14 23:26:26 +02:00
data_[(i >> 2)] |= ones() ^ dynamic_2bitset::vmask[i & 3];
2012-03-14 21:43:38 +02:00
data_[(i >> 2)] &= ((v << ((i & 3) << 1)) | dynamic_2bitset::vmask[i & 3]);
2012-03-14 23:26:26 +02:00
assert(v <= 3);
2012-03-14 21:43:38 +02:00
assert(get(i) == v);
}
void resize(uint32_t size) {
size_ = size;
2012-03-14 23:26:26 +02:00
data_.resize(size >> 2, fill_*ones());
2012-03-14 21:43:38 +02:00
}
2012-03-14 23:26:26 +02:00
void swap(dynamic_2bitset& other) {
std::swap(other.size_, size_);
std::swap(other.fill_, fill_);
std::swap(other.data_, data_);
}
void clear() { data_.clear(); }
uint32_t size() const { return size_; }
2012-03-14 21:43:38 +02:00
static const uint8_t vmask[];
private:
uint32_t size_;
2012-03-14 23:26:26 +02:00
bool fill_;
std::vector<uint8_t> data_;
2012-03-14 21:43:38 +02:00
uint8_t ones() { return std::numeric_limits<uint8_t>::max(); }
};
static void set_2bit_value(uint8_t *d, uint32_t i, uint8_t v) {
2012-03-14 21:43:38 +02:00
d[(i >> 2)] &= ((v << ((i & 3) << 1)) | dynamic_2bitset::vmask[i & 3]);
}
static uint32_t get_2bit_value(const uint8_t* d, uint32_t i) {
return (d[(i >> 2)] >> (((i & 3) << 1)) & 3);
}
static uint32_t nextpoweroftwo(uint32_t k) {
if (k == 0) return 1;
k--;
for (int i=1; i<sizeof(uint32_t)*CHAR_BIT; i<<=1) k = k | k >> i;
return k+1;
}
} // namespace cxxmph
#endif