Feature #633
Von Maximilian Seesslen vor 7 Tagen aktualisiert
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".
<pre><code class="cpp">
#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" );
</code></pre>
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".
<pre><code class="cpp">
#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" );
</code></pre>