|
fiber
|
TimePoint and DurationThe fiber library provides a fully overflow-aware timing system including:
These types integrate seamlessly with the C++ <chrono> standard library while being specifically optimized for bare-metal embedded systems. They allow safe and precise tracking of time using wraparound counters (hardware timer-style), while preserving intuitive arithmetic and comparison operations.
Unlike the standard std::chrono types which assume linear time, fiber’s types are built on ClockTick, which wraps and tracks tick values modulo an overflow:
a < b, b - a) work correctly even when the counter has wrapped.This means the clock counter must count to at least double the maximum interval between two time points that are to be reliably compared.
Note: The library is heavily optimised to avoid modulo operations and divisions. The fastest is to always use the full range of the integer datatype. If your hardware timer does not cover the full range, for example a 10 or 24-bit counter, then always make sure that the counter overflows on a power of 2 / the maximal value is 2^n-1. ⚠️ If arbitrary overflows are used, the library will use additional modulo operations, but only for constructions (can be mittigated by using ClockTick::reinterpret) and multiplication.
<chrono>fiber::Duration, fiber::TimePoint, and fiber::Clock all follow the exact semantics and layout of their standard counterparts:
fiber::Duration is a wrapper around std::chrono::duration using ClockTick as its representation type.fiber::TimePoint wraps std::chrono::time_point using your chosen Clock.std::chrono::duration_cast or fiber::rounding_duration_cast.You can freely mix fiber clocks with standard std::chrono durations where appropriate.
Creating a custom hardware-aware overflow-safe clock is extremely simple. All you need to provide is:
uint32_t)std::ratio expressing its period relative to 1s (e.g. std::micro if each tick represents a micro second)constexpr function that returns the current counter value⚠️ The fourth template argument is the maximum value the counter counts to, not the value after overflow.
Once defined, you can use this clock directly:
Clock_test.cpp)Fiber or any cooperative schedulerfiber makes working with microcontroller timers as safe and intuitive as modern C++ chrono types — without giving up performance or hardware alignment. You keep full control over the tick source, overflow range, and resolution, and the library guarantees that comparisons and arithmetic Just Work™.