compare-inl.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #ifndef COMPARE_INL_H_
  2. #error "Direct inclusion of this file is not allowed, include compare.h"
  3. // For the sake of sane code completion.
  4. #include "compare.h"
  5. #endif
  6. #include "numeric_helpers.h"
  7. #include <util/generic/string.h>
  8. #include <string>
  9. #include <string_view>
  10. namespace NYT {
  11. ////////////////////////////////////////////////////////////////////////////////
  12. template <class T>
  13. Y_FORCE_INLINE int TernaryCompare(const T& lhs, const T& rhs)
  14. {
  15. if (lhs == rhs) {
  16. return 0;
  17. } else if (lhs < rhs) {
  18. return -1;
  19. } else {
  20. return +1;
  21. }
  22. }
  23. //! An optimized version for string types.
  24. template <class T>
  25. requires
  26. std::is_same_v<T, TString> ||
  27. std::is_same_v<T, TStringBuf> ||
  28. std::is_same_v<T, std::string> ||
  29. std::is_same_v<T, std::string_view>
  30. Y_FORCE_INLINE int TernaryCompare(const T& lhs, const T& rhs)
  31. {
  32. return GetSign(std::string_view(lhs).compare(std::string_view(rhs)));
  33. }
  34. template <class T>
  35. Y_FORCE_INLINE int NaNSafeTernaryCompare(const T& lhs, const T& rhs)
  36. {
  37. return TernaryCompare(lhs, rhs);
  38. }
  39. template <class T>
  40. requires std::is_floating_point_v<T>
  41. Y_FORCE_INLINE int NaNSafeTernaryCompare(const T& lhs, const T& rhs)
  42. {
  43. if (lhs < rhs) {
  44. return -1;
  45. } else if (lhs > rhs) {
  46. return +1;
  47. } else if (std::isnan(lhs)) {
  48. if (std::isnan(rhs)) {
  49. return 0;
  50. } else {
  51. return +1;
  52. }
  53. } else if (std::isnan(rhs)) {
  54. return -1;
  55. } else {
  56. return 0;
  57. }
  58. }
  59. ////////////////////////////////////////////////////////////////////////////////
  60. } // namespace NYT