clamp.hpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_CORE_DETAIL_CLAMP_HPP
  10. #define BOOST_BEAST_CORE_DETAIL_CLAMP_HPP
  11. #include <cstdlib>
  12. #include <limits>
  13. #include <type_traits>
  14. namespace boost {
  15. namespace beast {
  16. namespace detail {
  17. template<class UInt>
  18. static
  19. std::size_t
  20. clamp(UInt x)
  21. {
  22. if(x >= (std::numeric_limits<std::size_t>::max)())
  23. return (std::numeric_limits<std::size_t>::max)();
  24. return static_cast<std::size_t>(x);
  25. }
  26. template<class UInt>
  27. static
  28. std::size_t
  29. clamp(UInt x, std::size_t limit)
  30. {
  31. if(x >= limit)
  32. return limit;
  33. return static_cast<std::size_t>(x);
  34. }
  35. // return `true` if x + y > z, which are unsigned
  36. template<
  37. class U1, class U2, class U3>
  38. constexpr
  39. bool
  40. sum_exceeds(U1 x, U2 y, U3 z)
  41. {
  42. static_assert(
  43. std::is_unsigned<U1>::value &&
  44. std::is_unsigned<U2>::value &&
  45. std::is_unsigned<U3>::value, "");
  46. return y > z || x > z - y;
  47. }
  48. } // detail
  49. } // beast
  50. } // boost
  51. #endif