MeshLib C++ Docs
Loading...
Searching...
No Matches
MRNextUpDown.h
Go to the documentation of this file.
1#pragma once
2
3#include "MRBitCast.h"
4#include <cmath>
5#include <cstdint>
6#include <limits>
7#include <type_traits>
8
9namespace MR
10{
13
14
15namespace detail
16{
17
19template <typename T>
20[[nodiscard]] inline auto signStep( T x )
21{
22 using U = std::conditional_t<std::is_same_v<T, float>, std::uint32_t, std::uint64_t>;
23 using S = std::make_signed_t<U>;
24 return U( U( S( bit_cast<U>( x ) ) >> ( 8 * sizeof( U ) - 1 ) ) | 1 );
25}
26
28template <typename T>
29[[nodiscard]] inline bool nonzeroBelowMax( T x )
30{
31 using U = decltype( signStep( x ) );
32 constexpr U absMask = U( -1 ) >> 1;
33 return U( ( bit_cast<U>( x ) & absMask ) - 1 ) < U( bit_cast<U>( std::numeric_limits<T>::max() ) - 1 );
34}
35
36}
37
40template <typename T>
41[[nodiscard]] inline T nextUp( T x )
42{
43 if constexpr ( std::is_same_v<T, float> || std::is_same_v<T, double> )
44 {
46 if ( detail::nonzeroBelowMax( x ) )
47 return bit_cast<T>( bit_cast<decltype( detail::signStep( x ) )>( x ) + detail::signStep( x ) );
48 }
49 return std::nextafter( x, std::numeric_limits<T>::max() );
50}
51
54template <typename T>
55[[nodiscard]] inline T nextDown( T x )
56{
57 if constexpr ( std::is_same_v<T, float> || std::is_same_v<T, double> )
58 {
59 if ( detail::nonzeroBelowMax( x ) )
60 return bit_cast<T>( bit_cast<decltype( detail::signStep( x ) )>( x ) - detail::signStep( x ) );
61 }
62 return std::nextafter( x, std::numeric_limits<T>::lowest() );
63}
64
65}
T nextUp(T x)
Definition MRNextUpDown.h:41
auto signStep(T x)
+1 for positive x and -1 (all bits set) for negative x, as an unsigned integer of the same size as x
Definition MRNextUpDown.h:20
bool nonzeroBelowMax(T x)
whether 0 < |x| < max: then the closest values around x differ from it by one in the bits; one unsign...
Definition MRNextUpDown.h:29
T nextDown(T x)
Definition MRNextUpDown.h:55
constexpr To bit_cast(const From &from) noexcept
std::bit_cast wrapper with the compiler's intrinsic fallback
Definition MRBitCast.h:17
for internal use: namespace detail is not bound to other languages
Definition MRAllocator.h:23
Only strictly necessary for the bindings (to make MR::MeshIntersectionResult a complete type).
Definition MRCameraOrientationPlugin.h:8