#pragma once #include "typetraits.h" #include template static constexpr const T& Min(const T& l, const T& r) { return r < l ? r : l; } template static constexpr const T& Min(const T& a, const T& b, const Args&... args) { return Min(a, Min(b, args...)); } template static constexpr const T& Max(const T& l, const T& r) { return l < r ? r : l; } template static constexpr const T& Max(const T& a, const T& b, const Args&... args) { return Max(a, Max(b, args...)); } // replace with http://en.cppreference.com/w/cpp/algorithm/clamp in c++17 template constexpr const T& ClampVal(const T& val, const T& min, const T& max) { return val < min ? min : (max < val ? max : val); } template static T Mean(const Args&... other) noexcept { const auto numArgs = sizeof...(other); auto sum = T(); for (const auto& v : {other...}) { sum += v; } return sum / numArgs; } template static inline void Zero(T& t) noexcept { memset((void*)&t, 0, sizeof(t)); } /** * Securely zero memory (compiler does not optimize this out) * * @param pointer void pointer to start of memory block to be zeroed * @param count size of memory block to be zeroed (in bytes) */ void SecureZero(void* pointer, size_t count) noexcept; /** * Securely zero memory of given object (compiler does not optimize this out) * * @param t reference to object, which must be zeroed */ template static inline void SecureZero(T& t) noexcept { SecureZero((void*)&t, sizeof(t)); } namespace NSwapCheck { Y_HAS_MEMBER(swap); Y_HAS_MEMBER(Swap); template struct TSwapSelector { static inline void Swap(T& l, T& r) noexcept(std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value) { T tmp(std::move(l)); l = std::move(r); r = std::move(tmp); } }; template struct TSwapSelector::value>> { static inline void Swap(T& l, T& r) noexcept(noexcept(l.Swap(r))) { l.Swap(r); } }; template struct TSwapSelector::value && !THasSwap::value>> { static inline void Swap(T& l, T& r) noexcept(noexcept(l.swap(r))) { l.swap(r); } }; } /* * DoSwap better than ::Swap in member functions... */ template static inline void DoSwap(T& l, T& r) noexcept(noexcept(NSwapCheck::TSwapSelector::Swap(l, r))) { NSwapCheck::TSwapSelector::Swap(l, r); } template struct TNullTmpl { template operator T() const { return (T)0; } }; using TNull = TNullTmpl<0>; /* * Class for zero-initialize padding bytes in derived classes */ template class TZeroInit { protected: TZeroInit() { // Actually, safe because this as TDerived is not initialized yet. Zero(*static_cast(this)); } }; struct TIdentity { template constexpr decltype(auto) operator()(T&& x) const noexcept { return std::forward(x); } };