AP_Common: make Bitmask a template on number of bits

This commit is contained in:
Peter Barker 2019-04-11 22:12:26 +10:00 committed by Andrew Tridgell
parent 4e494d5a63
commit e51a0a7a52
3 changed files with 11 additions and 34 deletions

View File

@ -1,24 +0,0 @@
#include "Bitmask.h"
#include <AP_HAL/AP_HAL.h>
Bitmask &Bitmask::operator=(const Bitmask&other)
{
if (other.numwords != numwords || other.numbits != numbits) {
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
// we really should not be assigning from a bitmask of a
// different number of bits!
AP_HAL::panic("attempt to copy from bitmask of different size");
#endif
// ... but try to cope if it happens in real life:
if (numwords != other.numwords) {
delete bits;
bits = new uint32_t[numwords];
numwords = other.numwords;
}
numbits = other.numbits;
}
memcpy(bits, other.bits, sizeof(bits[0])*other.numwords);
return *this;
}

View File

@ -21,19 +21,20 @@
#include <stdint.h>
#include <string.h>
template<uint16_t num_bits>
class Bitmask {
public:
Bitmask(uint16_t num_bits) :
Bitmask() :
numbits(num_bits),
numwords((num_bits+31)/32) {
bits = new uint32_t[numwords];
clearall();
}
~Bitmask(void) {
delete[] bits;
Bitmask &operator=(const Bitmask&other) {
memcpy(bits, other.bits, sizeof(bits[0])*other.numwords);
return *this;
}
Bitmask &operator=(const Bitmask&other);
Bitmask(const Bitmask &other) = delete;
// set given bitnumber
@ -129,5 +130,5 @@ public:
private:
uint16_t numbits;
uint16_t numwords;
uint32_t *bits;
uint32_t bits[(num_bits+31)/32];
};

View File

@ -4,7 +4,7 @@
TEST(Bitmask, Tests)
{
Bitmask x{49};
Bitmask<49> x;
EXPECT_EQ(-1, x.first_set());
x.set(5);
@ -40,7 +40,7 @@ TEST(Bitmask, Tests)
TEST(Bitmask, SetAll)
{
Bitmask x{49};
Bitmask<49> x;
EXPECT_EQ(-1, x.first_set());
EXPECT_EQ(false, x.get(45));
x.setall();
@ -59,13 +59,13 @@ TEST(Bitmask, SetAll)
TEST(Bitmask, Assignment)
{
Bitmask x{49};
Bitmask<49> x;
x.set(0);
x.set(5);
x.set(6);
x.set(48);
Bitmask y{49};
Bitmask<49> y;
y = x;
x.clear(0);
EXPECT_EQ(true, y.get(0));