diff --git a/data/FixedSizeData.h b/data/FixedSizeData.h index a589de91..c5aa84fe 100644 --- a/data/FixedSizeData.h +++ b/data/FixedSizeData.h @@ -30,8 +30,12 @@ public: const unsigned char *data() const; unsigned char *data(); + template FixedSizeData take() const; + template FixedSizeData drop() const; + private: FixedSizeData() {} + template friend class FixedSizeData; unsigned char _data[BINARY_LENGTH]; }; @@ -97,6 +101,22 @@ FixedSizeData FixedSizeData::FromBinary(const void *source) { return result; } +template template +FixedSizeData FixedSizeData::take() const { + static_assert(size <= SIZE, "Out of bounds"); + FixedSizeData result; + std::memcpy(result._data, _data, size); + return result; +} + +template template +FixedSizeData FixedSizeData::drop() const { + static_assert(size <= SIZE, "Out of bounds"); + FixedSizeData result; + std::memcpy(result._data, _data+size, SIZE-size); + return result; +} + template bool operator==(const FixedSizeData &lhs, const FixedSizeData &rhs) { return 0 == std::memcmp(lhs.data(), rhs.data(), FixedSizeData::BINARY_LENGTH); diff --git a/test/data/FixedSizeDataTest.cpp b/test/data/FixedSizeDataTest.cpp index b043a8ac..9b4a75b9 100644 --- a/test/data/FixedSizeDataTest.cpp +++ b/test/data/FixedSizeDataTest.cpp @@ -116,6 +116,52 @@ TEST_P(FixedSizeDataTestWithParam, CopyConstructor) { EXPECT_EQ(GetParam(), copy); } +TEST_P(FixedSizeDataTestWithParam, Take_Half) { + FixedSizeData source(GetParam()); + FixedSizeData taken = source.take(); + EXPECT_EQ(0, std::memcmp(source.data(), taken.data(), SIZE/2)); +} + +TEST_P(FixedSizeDataTestWithParam, Drop_Half) { + FixedSizeData source(GetParam()); + FixedSizeData taken = source.drop(); + EXPECT_EQ(0, std::memcmp(source.data() + SIZE/2, taken.data(), SIZE/2)); +} + +TEST_P(FixedSizeDataTestWithParam, Take_One) { + FixedSizeData source(GetParam()); + FixedSizeData<1> taken = source.take<1>(); + EXPECT_EQ(0, std::memcmp(source.data(), taken.data(), 1)); +} + +TEST_P(FixedSizeDataTestWithParam, Drop_One) { + FixedSizeData source(GetParam()); + FixedSizeData taken = source.drop<1>(); + EXPECT_EQ(0, std::memcmp(source.data() + 1, taken.data(), SIZE-1)); +} + +TEST_P(FixedSizeDataTestWithParam, Take_Nothing) { + FixedSizeData source(GetParam()); + FixedSizeData<0> taken = source.take<0>(); +} + +TEST_P(FixedSizeDataTestWithParam, Drop_Nothing) { + FixedSizeData source(GetParam()); + FixedSizeData taken = source.drop<0>(); + EXPECT_EQ(0, std::memcmp(source.data(), taken.data(), SIZE)); +} + +TEST_P(FixedSizeDataTestWithParam, Take_All) { + FixedSizeData source(GetParam()); + FixedSizeData taken = source.take(); + EXPECT_EQ(0, std::memcmp(source.data(), taken.data(), SIZE)); +} + +TEST_P(FixedSizeDataTestWithParam, Drop_All) { + FixedSizeData source(GetParam()); + FixedSizeData<0> taken = source.drop(); +} + TEST_F(FixedSizeDataTest, CopyConstructorDoesntChangeSource) { FixedSizeData data1 = FixedSizeData::FromString(DATA1_AS_STRING); FixedSizeData data2(data1);