numeric_helpers-inl.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #ifndef NUMERIC_HELPERS_INL_H_
  2. #error "Direct inclusion of this file is not allowed, include numeric_helpers.h"
  3. // For the sake of sane code completion.
  4. #include "numeric_helpers.h"
  5. #endif
  6. #include <cstdlib>
  7. #include <cinttypes>
  8. #include <cmath>
  9. #include <algorithm>
  10. #include <util/system/compiler.h>
  11. namespace NYT {
  12. ////////////////////////////////////////////////////////////////////////////////
  13. template <class T>
  14. T DivCeil(const T& numerator, const T& denominator)
  15. {
  16. YT_VERIFY(denominator != 0);
  17. auto res = std::div(numerator, denominator);
  18. return res.quot + (res.rem > static_cast<T>(0) ? static_cast<T>(1) : static_cast<T>(0));
  19. }
  20. template <typename T>
  21. T DivRound(const T& numerator, const T& denominator)
  22. {
  23. auto res = std::div(numerator, denominator);
  24. return res.quot + (res.rem >= (denominator + 1) / 2 ? static_cast<T>(1) : static_cast<T>(0));
  25. }
  26. template <class T>
  27. T RoundUp(const T& numerator, const T& denominator)
  28. {
  29. return DivCeil(numerator, denominator) * denominator;
  30. }
  31. template <class T>
  32. T RoundDown(const T& numerator, const T& denominator)
  33. {
  34. return (numerator / denominator) * denominator;
  35. }
  36. template <class T>
  37. Y_FORCE_INLINE int GetSign(const T& value)
  38. {
  39. if (value < 0) {
  40. return -1;
  41. } else if (value > 0) {
  42. return +1;
  43. } else {
  44. return 0;
  45. }
  46. }
  47. ////////////////////////////////////////////////////////////////////////////////
  48. } // namespace NYT