Browse Source

to string for bit array

Kajetan Johannes Hammerle 3 years ago
parent
commit
4a0a373bb3
2 changed files with 43 additions and 4 deletions
  1. 28 4
      tests/BitArrayTests.cpp
  2. 15 0
      utils/BitArray.h

+ 28 - 4
tests/BitArrayTests.cpp

@@ -1,6 +1,9 @@
 #include "tests/BitArrayTests.h"
 #include "tests/Test.h"
 #include "utils/BitArray.h"
+#include "utils/StringBuffer.h"
+
+typedef StringBuffer<50> String;
 
 static void testSetRead(Test& test) {
     BitArray<4, 3> bits;
@@ -58,10 +61,29 @@ static void testChainedSet(Test& test) {
     BitArray<4, 3> bits;
     bits[0] = bits[2] = bits[3] = 2;
     bits[3] = bits[1] = 7;
-    test.checkEqual(2, static_cast<int>(bits[0]), "chained set sets correct value");
-    test.checkEqual(7, static_cast<int>(bits[1]), "chained set sets correct value");
-    test.checkEqual(2, static_cast<int>(bits[2]), "chained set sets correct value");
-    test.checkEqual(7, static_cast<int>(bits[3]), "chained set sets correct value");
+    test.checkEqual(2, static_cast<int> (bits[0]), "chained set sets correct value");
+    test.checkEqual(7, static_cast<int> (bits[1]), "chained set sets correct value");
+    test.checkEqual(2, static_cast<int> (bits[2]), "chained set sets correct value");
+    test.checkEqual(7, static_cast<int> (bits[3]), "chained set sets correct value");
+}
+
+static void testToString1(Test& test) {
+    BitArray<4, 3> bits;
+    bits[0] = 1;
+    bits[1] = 2;
+    bits[2] = 3;
+    bits[3] = 4;
+    String s;
+    s.append(bits);
+    test.checkEqual(String("[1, 2, 3, 4]"), s, "bit array to string 1");
+}
+
+static void testToString2(Test& test) {
+    BitArray<1, 3> a;
+    a[0] = 1;
+    String s;
+    s.append(a);
+    test.checkEqual(String("[1]"), s, "bit array to string 1");
 }
 
 void BitArrayTests::test() {
@@ -71,5 +93,7 @@ void BitArrayTests::test() {
     testRandomSetRead(test);
     testReadOnly(test);
     testChainedSet(test);
+    testToString1(test);
+    testToString2(test);
     test.finalize();
 }

+ 15 - 0
utils/BitArray.h

@@ -3,6 +3,8 @@
 
 #include <iostream>
 
+#include "utils/StringBuffer.h"
+
 template<int N, int BITS>
 class BitArray final {
     static constexpr int INT_BITS = sizeof (int) * 8;
@@ -107,6 +109,19 @@ public:
     constexpr int getLength() const {
         return N;
     }
+    
+    template<int L>
+    void toString(StringBuffer<L>& s) const {
+        s.append("[");
+        for(int i = 0; i < N - 1; i++) {
+            s.append((*this)[i]);
+            s.append(", ");
+        }
+        if(N > 0) {
+            s.append((*this)[N - 1]);
+        }
+        s.append("]");
+    }
 };
 
 #endif