John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 1 | #ifndef AOS_UTIL_WRAPPING_COUNTER_H_ |
| 2 | #define AOS_UTIL_WRAPPING_COUNTER_H_ |
Brian Silverman | 2f59450 | 2013-10-16 10:29:47 -0700 | [diff] [blame] | 3 | |
Tyler Chatow | bf0609c | 2021-07-31 16:13:27 -0700 | [diff] [blame] | 4 | #include <cstdint> |
Brian Silverman | 2f59450 | 2013-10-16 10:29:47 -0700 | [diff] [blame] | 5 | |
Stephan Pleines | d99b1ee | 2024-02-02 20:56:44 -0800 | [diff] [blame] | 6 | namespace aos::util { |
Brian Silverman | 2f59450 | 2013-10-16 10:29:47 -0700 | [diff] [blame] | 7 | |
| 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). |
| 12 | class 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 Pleines | d99b1ee | 2024-02-02 20:56:44 -0800 | [diff] [blame] | 30 | } // namespace aos::util |
Brian Silverman | 2f59450 | 2013-10-16 10:29:47 -0700 | [diff] [blame] | 31 | |
John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 32 | #endif // AOS_UTIL_WRAPPING_COUNTER_H_ |