#pragma once
#include <stdint.h>
#include <string.h>
#include <AP_InternalError/AP_InternalError.h>
template<uint16_t NUMBITS>
class Bitmask {
static constexpr uint16_t NUMWORDS = ((NUMBITS+31)/32);
static_assert(NUMBITS > 0, "must store something");
static_assert(NUMBITS <= INT16_MAX, "must fit in int16_t");
static_assert(sizeof(unsigned int) >= sizeof(uint32_t), "int too small");
public:
Bitmask() {
clearall();
}
Bitmask &operator=(const Bitmask&other) {
memcpy(bits, other.bits, sizeof(bits[0])*NUMWORDS);
return *this;
}
bool operator==(const Bitmask&other) {
return memcmp(bits, other.bits, sizeof(bits[0])*NUMWORDS) == 0;
}
bool operator!=(const Bitmask&other) {
return !(*this == other);
}
Bitmask(const Bitmask &other) = delete;
template<size_t N>
Bitmask(const uint16_t (&enabled_bits)[N]) {
clearall();
for (size_t i = 0; i < N; ++i) {
if (enabled_bits[i] < NUMBITS) {
set(enabled_bits[i]);
}
}
}
void set(uint16_t bit) {
if (!validate(bit)) {
return;
}
uint16_t word = bit/32;
uint8_t ofs = bit & 0x1f;
bits[word] |= (1U << ofs);
}
void setall(void) {
for (uint16_t i=0; i<NUMWORDS; i++) {
bits[i] = 0xffffffff;
}
uint16_t num_valid_bits = NUMBITS % 32;
if (num_valid_bits) {
bits[NUMWORDS-1] = (1U << num_valid_bits) - 1;
}
}
void clear(uint16_t bit) {
if (!validate(bit)) {
return;
}
uint16_t word = bit/32;
uint8_t ofs = bit & 0x1f;
bits[word] &= ~(1U << ofs);
}
void setonoff(uint16_t bit, bool onoff) {
if (onoff) {
set(bit);
} else {
clear(bit);
}
}
void clearall(void) {
memset(bits, 0, NUMWORDS*sizeof(bits[0]));
}
bool get(uint16_t bit) const {
if (!validate(bit)) {
return false;
}
uint16_t word = bit/32;
uint8_t ofs = bit & 0x1f;
return (bits[word] & (1U << ofs)) != 0;
}
bool empty(void) const {
for (uint16_t i=0; i<NUMWORDS; i++) {
if (bits[i] != 0) {
return false;
}
}
return true;
}
uint16_t count() const {
uint16_t sum = 0;
for (uint16_t i=0; i<NUMWORDS; i++) {
sum += __builtin_popcount(bits[i]);
}
return sum;
}
int16_t first_set() const {
for (uint16_t i=0; i<NUMWORDS; i++) {
if (bits[i] != 0) {
return i*32 + __builtin_ffs(bits[i]) - 1;
}
}
return -1;
}
uint16_t size() const {
return NUMBITS;
}
private:
bool validate(uint16_t bit) const {
if (bit >= NUMBITS) {
INTERNAL_ERROR(AP_InternalError::error_t::bitmask_range);
return false;
}
return true;
}
uint32_t bits[NUMWORDS];
};