include/xot/util.h in xot-0.1.12 vs include/xot/util.h in xot-0.1.13

- old
+ new

@@ -4,10 +4,11 @@ #define __XOT_UTIL_H__ #include <stdint.h> #include <math.h> +#include <assert.h> #include <xot/defs.h> #include <xot/time.h> namespace Xot @@ -24,49 +25,103 @@ double random (double max_ = 1); double random (double min_, double max_); + template <typename T = uint> + inline constexpr T + bit (int nth, T base = 0x1) + { + return (T) (base << nth); + } + template <typename T> - inline T deg2rad (T degree) + inline constexpr T + clip (T minval, T maxval, T value) { - return degree / (T) 180 * M_PI; + return value > maxval ? maxval : (value < minval ? minval : value); } + + inline constexpr double + deg2rad (double degree) + { + return degree / 180.0 * M_PI; + } + + inline constexpr double + rad2deg (double radian) + { + return radian / M_PI * 180.0; + } + + template <typename T> - inline T rad2deg (T radian) + inline void + add_flag (T* pvalue, uint flag) { - return radian / M_PI * (T) 180; + assert(pvalue); + + *pvalue |= flag; } + template <typename T> + inline void + remove_flag (T* pvalue, uint flag) + { + assert(pvalue); + *pvalue &= ~flag; + } + template <typename T> - inline T clip (T minval, T maxval, T value) + inline bool + has_flag (T value, uint flag) { - return value > maxval ? maxval : (value < minval ? minval : value); + if (flag == 0) return false; + return (value & flag) == flag; } + template <typename T> + inline bool + check_and_remove_flag (T* pvalue, uint flag) + { + assert(pvalue); + bool has = has_flag(*pvalue, flag); + remove_flag(pvalue, flag); + return has; + } + + + static const uintptr_t POINTER_FLAG = 0x1; + template <typename T> - inline T* set_pointer_flag (T* pointer, bool flag = true) + inline T* + set_pointer_flag (T* pointer, bool flag = true) { uintptr_t intval = *(uintptr_t*) &pointer; - if (flag) intval |= 0x1; - else intval &= ~0x1; + if (flag) + intval |= POINTER_FLAG; + else + intval &= ~POINTER_FLAG; + return *(T**) &intval; } template <typename T> - inline const T* set_pointer_flag (const T* pointer, bool flag = true) + inline const T* + set_pointer_flag (const T* pointer, bool flag = true) { return set_pointer_flag(const_cast<T*>(pointer), flag); } template <typename T> - inline bool get_pointer_flag (const T* pointer) + inline bool + get_pointer_flag (const T* pointer) { - uintptr_t intval = *(uintptr_t*) &pointer; - return intval & 0x1; + const uintptr_t& intval = *(uintptr_t*) &pointer; + return intval & POINTER_FLAG; } }// Xot