blob: ea79ec639d65323c6cd9e49321f5c2652bb29de1 [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
6namespace aos {
7namespace util {
8
9// Deals correctly with 1-byte counters which wrap.
10// This is only possible if the counter never wraps twice between Update calls.
11// It will also fail if the counter ever goes down (that will be interpreted as
12// +255 instead of -1, for example).
13class WrappingCounter {
14 public:
15 WrappingCounter(int32_t initial_count = 0);
16
17 // Updates the internal counter with a new raw value.
18 // Returns count() for convenience.
19 int32_t Update(uint8_t current);
20
21 // Resets the actual count to value.
22 void Reset(int32_t value = 0) { count_ = value; }
23
24 int32_t count() const { return count_; }
25
26 private:
27 int32_t count_;
28 uint8_t last_count_;
29};
30
31} // namespace util
32} // namespace aos
33
John Park33858a32018-09-28 23:05:48 -070034#endif // AOS_UTIL_WRAPPING_COUNTER_H_