From 004c9d8d0912d55960fd9c7f8b76572fcf1a5804 Mon Sep 17 00:00:00 2001 From: Joel Rosdahl Date: Sun, 26 Oct 2025 09:29:40 +0100 Subject: [PATCH] enhance: Add util::Bytes::at method --- src/ccache/util/bytes.cpp | 20 ++++++++++++++++++++ src/ccache/util/bytes.hpp | 3 +++ unittest/test_util_bytes.cpp | 24 ++++++++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/src/ccache/util/bytes.cpp b/src/ccache/util/bytes.cpp index 3bb76183..d3c82f43 100644 --- a/src/ccache/util/bytes.cpp +++ b/src/ccache/util/bytes.cpp @@ -20,6 +20,8 @@ #include +#include + namespace util { namespace { @@ -92,6 +94,24 @@ Bytes::operator=(std::string_view data) noexcept return *this; } +uint8_t +Bytes::at(size_t pos) const +{ + if (pos >= m_size) { + throw std::out_of_range("Bytes::at: pos >= size()"); + } + return m_data[pos]; +} + +uint8_t& +Bytes::at(size_t pos) +{ + if (pos >= m_size) { + throw std::out_of_range("Bytes::at: pos >= size()"); + } + return m_data[pos]; +} + void Bytes::reserve(size_t size) noexcept { diff --git a/src/ccache/util/bytes.hpp b/src/ccache/util/bytes.hpp index d7545e2a..56d394f3 100644 --- a/src/ccache/util/bytes.hpp +++ b/src/ccache/util/bytes.hpp @@ -60,6 +60,9 @@ public: uint8_t operator[](size_t pos) const noexcept; uint8_t& operator[](size_t pos) noexcept; + uint8_t at(size_t pos) const; + uint8_t& at(size_t pos); + bool operator==(const Bytes& other) const noexcept; bool operator!=(const Bytes& other) const noexcept; diff --git a/unittest/test_util_bytes.cpp b/unittest/test_util_bytes.cpp index c3a320c6..cc3bf3d6 100644 --- a/unittest/test_util_bytes.cpp +++ b/unittest/test_util_bytes.cpp @@ -189,6 +189,30 @@ TEST_CASE("Basics") CHECK(bytes1[1] == 'x'); // cppcheck-suppress knownConditionTrueFalse } + SUBCASE("at method") + { + // Const version + const Bytes& const_bytes = bytes1; + CHECK(const_bytes.at(0) == 'a'); + CHECK(const_bytes.at(1) == 'b'); + CHECK(const_bytes.at(2) == 'c'); + CHECK_THROWS_AS(const_bytes.at(3), std::out_of_range); + CHECK_THROWS_AS(const_bytes.at(100), std::out_of_range); + + // Non-const version + CHECK(bytes1.at(0) == 'a'); + CHECK(bytes1.at(1) == 'b'); + CHECK(bytes1.at(2) == 'c'); + bytes1.at(1) = 'x'; + CHECK(bytes1.at(1) == 'x'); + CHECK_THROWS_AS(bytes1.at(3), std::out_of_range); + CHECK_THROWS_AS(bytes1.at(100), std::out_of_range); + + // Empty + Bytes empty; + CHECK_THROWS_AS(empty.at(0), std::out_of_range); + } + SUBCASE("Comparison") { CHECK(bytes1 == bytes1); -- 2.47.3