diff --git a/QRCodeLibrary/BitArray.cpp b/QRCodeLibrary/BitArray.cpp index 476a654..8a172c2 100644 --- a/QRCodeLibrary/BitArray.cpp +++ b/QRCodeLibrary/BitArray.cpp @@ -6,6 +6,8 @@ bool BitArray::get(unsigned index) const { + if (index >= size) throw std::out_of_range("No such element in array"); + return (v[index / 8] >> (8 - 1 - index % 8)) & 1; } @@ -21,6 +23,8 @@ BitArray::operator std::string() const void BitArray::set(unsigned index, bool val) { + if (index >= size) throw std::out_of_range("No such element in array"); + if (val) v[index / 8] |= 1 << (8 - 1 - index % 8); else @@ -29,8 +33,12 @@ void BitArray::set(unsigned index, bool val) unsigned BitArray::set(unsigned index, int32_t val, unsigned size) { + if (index >= this->size) throw std::out_of_range("No such element in array"); + unsigned shift = index % 8, written = 0; - size = std::min(size, this->size - index); + + if (size > this->size - index) throw std::out_of_range("Number of bits to write from this index is more than BitArray capability"); + index /= 8; while (written < size) { @@ -48,3 +56,10 @@ unsigned BitArray::set(unsigned index, int32_t val, unsigned size) return written; } + +void BitArray::resize(unsigned new_size) +{ + v.resize(ceil_div(new_size, 8)); + + size = new_size; +} diff --git a/QRCodeLibrary/BitArray.hpp b/QRCodeLibrary/BitArray.hpp index 63d43e9..53d0dd6 100644 --- a/QRCodeLibrary/BitArray.hpp +++ b/QRCodeLibrary/BitArray.hpp @@ -22,5 +22,7 @@ public: bool get(unsigned index) const; void set(unsigned index, bool val); unsigned set(unsigned index, int32_t val, unsigned size); + + void resize(unsigned new_size); }; diff --git a/tests/BitArray_test.cpp b/tests/BitArray_test.cpp index 98c5063..c1c9922 100644 --- a/tests/BitArray_test.cpp +++ b/tests/BitArray_test.cpp @@ -5,6 +5,12 @@ #include "../QRCodeLibrary/BitArray.hpp" +TEST(CeilDivTests, DividesCeilingResult) { + EXPECT_EQ(ceil_div(1, 3), 1); + EXPECT_EQ(ceil_div(4, 2), 2); + EXPECT_EQ(ceil_div(5, 2), 3); +} + class BitArrayTests: public ::testing::Test { public: BitArrayTests() : ::testing::Test(), a1(15) {};