]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
enhance: Add util::Bytes::at method
authorJoel Rosdahl <joel@rosdahl.net>
Sun, 26 Oct 2025 08:29:40 +0000 (09:29 +0100)
committerJoel Rosdahl <joel@rosdahl.net>
Sun, 26 Oct 2025 15:13:16 +0000 (16:13 +0100)
src/ccache/util/bytes.cpp
src/ccache/util/bytes.hpp
unittest/test_util_bytes.cpp

index 3bb761834b54671de4a63cdac0335761d8d0df47..d3c82f430faf822aaa999ccd29afb5ac75959caf 100644 (file)
@@ -20,6 +20,8 @@
 
 #include <ccache/util/assertions.hpp>
 
+#include <stdexcept>
+
 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
 {
index d7545e2a57944d010734057a9ddece124ecdd46c..56d394f32df702ebb8a6d9c00071d5252bd2b54f 100644 (file)
@@ -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;
 
index c3a320c6fca2e29702b8a5c687e79f3212337309..cc3bf3d67f7d6c7a68b96d2ad4470db0e5e875b4 100644 (file)
@@ -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);