From 747a2576164e5f15f4f2a664f0608214cc13fc78 Mon Sep 17 00:00:00 2001 From: Joel Rosdahl Date: Sun, 26 Oct 2025 09:34:45 +0100 Subject: [PATCH] enhance: Add util::Bytes::push_back method --- src/ccache/util/bytes.cpp | 10 +++++++ src/ccache/util/bytes.hpp | 2 ++ unittest/test_util_bytes.cpp | 55 ++++++++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+) diff --git a/src/ccache/util/bytes.cpp b/src/ccache/util/bytes.cpp index d3c82f43..e4f54630 100644 --- a/src/ccache/util/bytes.cpp +++ b/src/ccache/util/bytes.cpp @@ -158,6 +158,16 @@ Bytes::insert(const uint8_t* pos, m_size += inserted_size; } +void +Bytes::push_back(uint8_t value) noexcept +{ + if (m_size >= m_capacity) { + reserve(m_capacity == 0 ? 1 : 2 * m_capacity); + } + m_data[m_size] = value; + ++m_size; +} + void Bytes::resize(size_t size) noexcept { diff --git a/src/ccache/util/bytes.hpp b/src/ccache/util/bytes.hpp index 56d394f3..2780de07 100644 --- a/src/ccache/util/bytes.hpp +++ b/src/ccache/util/bytes.hpp @@ -85,6 +85,8 @@ public: void clear() noexcept; void resize(size_t size) noexcept; // Note: New bytes will be uninitialized. + void push_back(uint8_t value) noexcept; + void insert(const uint8_t* pos, const uint8_t* first, const uint8_t* last) noexcept; diff --git a/unittest/test_util_bytes.cpp b/unittest/test_util_bytes.cpp index cc3bf3d6..2ea2f6b8 100644 --- a/unittest/test_util_bytes.cpp +++ b/unittest/test_util_bytes.cpp @@ -551,6 +551,61 @@ TEST_CASE("Basics") CHECK(bytes2[0] == 'x'); CHECK(bytes2[1] == 'z'); } + + SUBCASE("Push to back") + { + // Push to empty bytes + Bytes bytes2; + CHECK(bytes2.size() == 0); + CHECK(bytes2.capacity() == 0); + + bytes2.push_back('a'); + REQUIRE(bytes2.size() == 1); + CHECK(bytes2.capacity() == 1); + CHECK(bytes2[0] == 'a'); + + // Push to non-empty bytes without reallocation + bytes2.push_back('b'); + REQUIRE(bytes2.size() == 2); + CHECK(bytes2.capacity() == 2); + CHECK(bytes2[0] == 'a'); + CHECK(bytes2[1] == 'b'); + + bytes2.push_back('c'); + REQUIRE(bytes2.size() == 3); + CHECK(bytes2.capacity() == 4); + CHECK(bytes2[0] == 'a'); + CHECK(bytes2[1] == 'b'); + CHECK(bytes2[2] == 'c'); + + // Push multiple items to trigger reallocation + for (uint8_t i = 0; i < 10; ++i) { + bytes2.push_back(i); + } + REQUIRE(bytes2.size() == 13); + CHECK(bytes2.capacity() == 16); + CHECK(bytes2[0] == 'a'); + CHECK(bytes2[1] == 'b'); + CHECK(bytes2[2] == 'c'); + CHECK(bytes2[3] == 0); + CHECK(bytes2[4] == 1); + CHECK(bytes2[12] == 9); + + // Push to bytes with reserved capacity + Bytes bytes3; + bytes3.reserve(10); + CHECK(bytes3.capacity() == 10); + CHECK(bytes3.size() == 0); + + for (uint8_t i = 0; i < 5; ++i) { + bytes3.push_back(i); + } + REQUIRE(bytes3.size() == 5); + CHECK(bytes3.capacity() == 10); // Should not reallocate + for (size_t i = 0; i < 5; ++i) { + CHECK(bytes3[i] == i); + } + } } TEST_CASE("Conversion to span") -- 2.47.3