Browse Source

bit array extension

Kajetan Johannes Hammerle 2 years ago
parent
commit
334e07c861
3 changed files with 19 additions and 8 deletions
  1. 16 6
      data/BitArray.cpp
  2. 2 1
      data/BitArray.h
  3. 1 1
      tests/BitArrayTests.cpp

+ 16 - 6
data/BitArray.cpp

@@ -40,9 +40,14 @@ static void setBits(int* data, int index, int bits, int value) {
     }
 }
 
+BitArray::BitArray() : length(0), bits(0), data(nullptr) {
+}
+
 BitArray::BitArray(int length, int bits)
-    : length(length), bits(bits),
-      data(new int[roundUpDivide(length * bits, sizeof(int))]) {
+    : length(length), bits(bits), data(nullptr) {
+    if(length > 0 && bits > 0) {
+        data = new int[roundUpDivide(length * bits, sizeof(int))];
+    }
 }
 
 BitArray::BitArray(const BitArray& other) : BitArray(other.length, other.bits) {
@@ -51,7 +56,7 @@ BitArray::BitArray(const BitArray& other) : BitArray(other.length, other.bits) {
     }
 }
 
-BitArray::BitArray(BitArray&& other) : length(0), bits(0), data(nullptr) {
+BitArray::BitArray(BitArray&& other) : BitArray() {
     swap(other);
 }
 
@@ -87,14 +92,19 @@ void BitArray::fill(int value) {
     }
 }
 
-void BitArray::resize(int newBits) {
-    int* newData = new int[roundUpDivide(length * newBits, sizeof(int))];
-    for(int i = 0; i < length; i++) {
+void BitArray::resize(int newLength, int newBits) {
+    int* newData = new int[roundUpDivide(newLength * newBits, sizeof(int))];
+    int end = Math::min(length, newLength);
+    for(int i = 0; i < end; i++) {
         setBits(newData, i, newBits, get(i));
     }
+    for(int i = end; i < newLength; i++) {
+        setBits(newData, i, newBits, 0);
+    }
     delete[] data;
     data = newData;
     bits = newBits;
+    length = newLength;
 }
 
 void BitArray::swap(BitArray& other) {

+ 2 - 1
data/BitArray.h

@@ -9,6 +9,7 @@ class BitArray final {
     int* data;
 
 public:
+    BitArray();
     BitArray(int length, int bits);
     BitArray(const BitArray& other);
     BitArray(BitArray&& other);
@@ -21,7 +22,7 @@ public:
     int getLength() const;
     int getBits() const;
 
-    void resize(int newBits);
+    void resize(int newLength, int newBits);
 
     void fill(int value);
 

+ 1 - 1
tests/BitArrayTests.cpp

@@ -41,7 +41,7 @@ static void testRandomSetReadResize(Test& test) {
         test.checkEqual(data[i], bits.get(i),
                         "set and read correct value with random input");
     }
-    bits.resize(bits.getBits() + 1);
+    bits.resize(bits.getLength(), bits.getBits() + 1);
     test.checkEqual(14, bits.getBits(), "corrects bits after resize");
     test.checkEqual(100, bits.getLength(), "correct length after resize");
     for(int i = 0; i < bits.getLength(); i++) {