Brian Silverman | 2f59450 | 2013-10-16 10:29:47 -0700 | [diff] [blame^] | 1 | #ifndef AOS_COMMON_UTIL_WRAPPING_COUNTER_H_ |
| 2 | #define AOS_COMMON_UTIL_WRAPPING_COUNTER_H_ |
| 3 | |
| 4 | #include <stdint.h> |
| 5 | |
| 6 | namespace aos { |
| 7 | namespace 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). |
| 13 | class 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 | |
| 34 | #endif // AOS_COMMON_UTIL_WRAPPING_COUNTER_H_ |