blob: 0353e2ed194e619829cb1475480e04481d4bbd0a [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#ifndef AOS_UTIL_WRAPPING_COUNTER_H_
2#define AOS_UTIL_WRAPPING_COUNTER_H_
Brian Silverman2f594502013-10-16 10:29:47 -07003
Tyler Chatowbf0609c2021-07-31 16:13:27 -07004#include <cstdint>
Brian Silverman2f594502013-10-16 10:29:47 -07005
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -08006namespace aos::util {
Brian Silverman2f594502013-10-16 10:29:47 -07007
8// Deals correctly with 1-byte counters which wrap.
9// This is only possible if the counter never wraps twice between Update calls.
10// It will also fail if the counter ever goes down (that will be interpreted as
11// +255 instead of -1, for example).
12class WrappingCounter {
13 public:
14 WrappingCounter(int32_t initial_count = 0);
15
16 // Updates the internal counter with a new raw value.
17 // Returns count() for convenience.
18 int32_t Update(uint8_t current);
19
20 // Resets the actual count to value.
21 void Reset(int32_t value = 0) { count_ = value; }
22
23 int32_t count() const { return count_; }
24
25 private:
26 int32_t count_;
27 uint8_t last_count_;
28};
29
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080030} // namespace aos::util
Brian Silverman2f594502013-10-16 10:29:47 -070031
John Park33858a32018-09-28 23:05:48 -070032#endif // AOS_UTIL_WRAPPING_COUNTER_H_