From: Joel Rosdahl Date: Fri, 11 Sep 2020 07:41:11 +0000 (+0200) Subject: Introduce Counters::{get,set}_raw X-Git-Tag: v4.0~107 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=df5c0ed3a70b581a011004ec114109ccdfd9634a;p=thirdparty%2Fccache.git Introduce Counters::{get,set}_raw Casting an integer to an enum class value is undefined behavior so let’s strive not to do that. --- diff --git a/src/Counters.cpp b/src/Counters.cpp index 01db7356c..1ec52e2e0 100644 --- a/src/Counters.cpp +++ b/src/Counters.cpp @@ -29,19 +29,33 @@ Counters::Counters() : m_counters(static_cast(Statistic::END)) uint64_t Counters::get(Statistic statistic) const { - assert(static_cast(statistic) < static_cast(Statistic::END)); - const size_t i = static_cast(statistic); - return i < m_counters.size() ? m_counters[i] : 0; + const auto index = static_cast(statistic); + assert(index < static_cast(Statistic::END)); + return index < m_counters.size() ? m_counters[index] : 0; } void Counters::set(Statistic statistic, uint64_t value) { - const auto i = static_cast(statistic); - if (i >= m_counters.size()) { - m_counters.resize(i + 1); + const auto index = static_cast(statistic); + assert(index < static_cast(Statistic::END)); + m_counters[index] = value; +} + +uint64_t +Counters::get_raw(size_t index) const +{ + assert(index < size()); + return m_counters[index]; +} + +void +Counters::set_raw(size_t index, uint64_t value) +{ + if (index >= m_counters.size()) { + m_counters.resize(index + 1); } - m_counters[i] = value; + m_counters[index] = value; } void @@ -54,7 +68,6 @@ Counters::increment(Statistic statistic, int64_t value) auto& counter = m_counters[i]; counter = std::max(static_cast(0), static_cast(counter + value)); - } } size_t diff --git a/src/Counters.hpp b/src/Counters.hpp index cc8177b9c..44dc0b726 100644 --- a/src/Counters.hpp +++ b/src/Counters.hpp @@ -33,6 +33,10 @@ public: uint64_t get(Statistic statistic) const; void set(Statistic statistic, uint64_t value); + + uint64_t get_raw(size_t index) const; + void set_raw(size_t index, uint64_t value); + void increment(Statistic statistic, int64_t value = 1); size_t size() const; diff --git a/src/stats.cpp b/src/stats.cpp index 70350f828..133da430f 100644 --- a/src/stats.cpp +++ b/src/stats.cpp @@ -173,7 +173,7 @@ stats_write(const std::string& path, const Counters& counters) { AtomicFile file(path, AtomicFile::Mode::text); for (size_t i = 0; i < counters.size(); ++i) { - file.write(fmt::format("{}\n", counters.get(static_cast(i)))); + file.write(fmt::format("{}\n", counters.get_raw(i))); } try { file.commit();