divide_round.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright 2019 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_NUMERICS_DIVIDE_ROUND_H_
  11. #define RTC_BASE_NUMERICS_DIVIDE_ROUND_H_
  12. #include <type_traits>
  13. #include "rtc_base/checks.h"
  14. #include "rtc_base/numerics/safe_compare.h"
  15. namespace webrtc {
  16. template <typename Dividend, typename Divisor>
  17. inline auto constexpr DivideRoundUp(Dividend dividend, Divisor divisor) {
  18. static_assert(std::is_integral<Dividend>(), "");
  19. static_assert(std::is_integral<Divisor>(), "");
  20. RTC_DCHECK_GE(dividend, 0);
  21. RTC_DCHECK_GT(divisor, 0);
  22. auto quotient = dividend / divisor;
  23. auto remainder = dividend % divisor;
  24. return quotient + (remainder > 0 ? 1 : 0);
  25. }
  26. template <typename Dividend, typename Divisor>
  27. inline auto constexpr DivideRoundToNearest(Dividend dividend, Divisor divisor) {
  28. static_assert(std::is_integral<Dividend>(), "");
  29. static_assert(std::is_integral<Divisor>(), "");
  30. RTC_DCHECK_GE(dividend, 0);
  31. RTC_DCHECK_GT(divisor, 0);
  32. auto half_of_divisor = (divisor - 1) / 2;
  33. auto quotient = dividend / divisor;
  34. auto remainder = dividend % divisor;
  35. return quotient + (rtc::SafeGt(remainder, half_of_divisor) ? 1 : 0);
  36. }
  37. } // namespace webrtc
  38. #endif // RTC_BASE_NUMERICS_DIVIDE_ROUND_H_