compare.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (c) 2022, Cppreference.com
  2. //
  3. // Distributed under the terms of the Copyright/CC-BY-SA License.
  4. //
  5. // The full license can be found at the address
  6. // https://en.cppreference.com/w/Cppreference:Copyright/CC-BY-SA
  7. /**
  8. * Backport of C++20 ``std::cmp_*`` functions for signed comparison.
  9. */
  10. #ifndef MAMBA_CORE_UTIL_COMPARE_HPP
  11. #define MAMBA_CORE_UTIL_COMPARE_HPP
  12. #include <type_traits>
  13. #if __cplusplus >= 202002L
  14. #define MAMBA_UTIL_COMPARE_DEPRECATED [[deprecated("Use C++20 functions with the same name")]]
  15. #else
  16. #define MAMBA_UTIL_COMPARE_DEPRECATED
  17. #endif
  18. namespace mamba::util
  19. {
  20. template <class T, class U>
  21. MAMBA_UTIL_COMPARE_DEPRECATED constexpr bool cmp_equal(T t, U u) noexcept
  22. {
  23. using UT = std::make_unsigned_t<T>;
  24. using UU = std::make_unsigned_t<U>;
  25. if constexpr (std::is_signed_v<T> == std::is_signed_v<U>)
  26. {
  27. return t == u;
  28. }
  29. else if constexpr (std::is_signed_v<T>)
  30. {
  31. return t < 0 ? false : UT(t) == u;
  32. }
  33. else
  34. {
  35. return u < 0 ? false : t == UU(u);
  36. }
  37. }
  38. template <class T, class U>
  39. MAMBA_UTIL_COMPARE_DEPRECATED constexpr bool cmp_not_equal(T t, U u) noexcept
  40. {
  41. return !cmp_equal(t, u);
  42. }
  43. template <class T, class U>
  44. MAMBA_UTIL_COMPARE_DEPRECATED constexpr bool cmp_less(T t, U u) noexcept
  45. {
  46. using UT = std::make_unsigned_t<T>;
  47. using UU = std::make_unsigned_t<U>;
  48. if constexpr (std::is_signed_v<T> == std::is_signed_v<U>)
  49. {
  50. return t < u;
  51. }
  52. else if constexpr (std::is_signed_v<T>)
  53. {
  54. return t < 0 ? true : UT(t) < u;
  55. }
  56. else
  57. {
  58. return u < 0 ? false : t < UU(u);
  59. }
  60. }
  61. template <class T, class U>
  62. MAMBA_UTIL_COMPARE_DEPRECATED constexpr bool cmp_greater(T t, U u) noexcept
  63. {
  64. return cmp_less(u, t);
  65. }
  66. template <class T, class U>
  67. MAMBA_UTIL_COMPARE_DEPRECATED constexpr bool cmp_less_equal(T t, U u) noexcept
  68. {
  69. return !cmp_greater(t, u);
  70. }
  71. template <class T, class U>
  72. MAMBA_UTIL_COMPARE_DEPRECATED constexpr bool cmp_greater_equal(T t, U u) noexcept
  73. {
  74. return !cmp_less(t, u);
  75. }
  76. }
  77. #endif