Feature #633
add distance.hpp
Beginn:
09.04.2025
Abgabedatum:
% erledigt:
0%
Geschätzter Aufwand:
CS Zielversion:
Beschreibung
Trivial function to handle overflows in counters.
Think about an package counter with 8Bit.
You want to check the continuity of packages and that no packages are lost.
E.g. you would check counter_new_package > counter_old_package. this will fail on overflow border.
but distance( counter_old_package, counter_new_package) will be correctly "1".
#include <type_traits>
template<typename T>
constexpr T distance( T c1, T c2)
{
static_assert(std::is_signed<T>::value, "Requires signed type");
return( c2 - c1 );
}
static_assert( distance( (char)127, (char)-128 ) == 1, "A" );
static_assert( distance( (char)-128, (char)127 ) == -1, "A" );
static_assert( distance( -1, 1 ) == 2, "A" );
static_assert( distance( ((char)0x7F), ((char)0x80) ) == 1, "A" );
static_assert( distance( ((char)0xFF), ((char)0x00) ) == 1, "B" );
static_assert( distance( ((char)0x80), ((char)0x7F) ) == -1, "C" );
static_assert( distance( ((char)0x00), ((char)0xFF) ) == -1, "D" );