diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 155fa2f6bad..d883ce146e9 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -256,6 +256,11 @@ template class StaticVector { } } + // Converting constructor from a smaller StaticVector of the same element type + template StaticVector(const StaticVector &other) : StaticVector(other.begin(), other.end()) { + static_assert(M <= N, "Source StaticVector cannot be larger than the destination"); + } + // Minimal vector-compatible interface - only what we actually use void push_back(const T &value) { if (count_ < N) { diff --git a/tests/components/core/helpers_test.cpp b/tests/components/core/helpers_test.cpp index 468185787f5..a9a940392f2 100644 --- a/tests/components/core/helpers_test.cpp +++ b/tests/components/core/helpers_test.cpp @@ -55,4 +55,32 @@ TEST(HelpersTest, Ilog10RoundTripMatchesLog10) { } } +TEST(StaticVectorTest, ConvertingConstructorFromSmaller) { + StaticVector small{0x03, 0x00, 0x10, 0x00, 0x01}; + StaticVector big = small; + ASSERT_EQ(big.size(), small.size()); + for (size_t i = 0; i < small.size(); i++) { + EXPECT_EQ(big[i], small[i]) << "mismatch at index " << i; + } +} + +TEST(StaticVectorTest, ConvertingConstructorPartiallyFilledAndEmpty) { + StaticVector partial{0xAA, 0xBB}; + StaticVector from_partial = partial; + ASSERT_EQ(from_partial.size(), 2u); + EXPECT_EQ(from_partial[0], 0xAA); + EXPECT_EQ(from_partial[1], 0xBB); + + StaticVector empty; + StaticVector from_empty = empty; + EXPECT_TRUE(from_empty.empty()); +} + +TEST(StaticVectorTest, ConvertingConstructorSameSize) { + StaticVector src{1, 2, 3}; + StaticVector dst = src; + ASSERT_EQ(dst.size(), 3u); + EXPECT_EQ(dst[2], 3); +} + } // namespace esphome