blob: 90c67fca3c9f79f9f744ba64d66845833286b878 [file] [log] [blame]
Danil Chapovalov33b83fd2019-09-18 15:48:23 +02001/*
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
11#ifndef RTC_BASE_NUMERICS_DIVIDE_ROUND_H_
12#define RTC_BASE_NUMERICS_DIVIDE_ROUND_H_
13
14#include <type_traits>
15
16#include "rtc_base/checks.h"
17#include "rtc_base/numerics/safe_compare.h"
18
19namespace webrtc {
20
21template <typename Dividend, typename Divisor>
22inline auto constexpr DivideRoundUp(Dividend dividend, Divisor divisor) {
23 static_assert(std::is_integral<Dividend>(), "");
24 static_assert(std::is_integral<Divisor>(), "");
25 RTC_DCHECK_GE(dividend, 0);
26 RTC_DCHECK_GT(divisor, 0);
27
28 auto quotient = dividend / divisor;
29 auto remainder = dividend % divisor;
30 return quotient + (remainder > 0 ? 1 : 0);
31}
32
33template <typename Dividend, typename Divisor>
34inline auto constexpr DivideRoundToNearest(Dividend dividend, Divisor divisor) {
35 static_assert(std::is_integral<Dividend>(), "");
36 static_assert(std::is_integral<Divisor>(), "");
Danil Chapovalov33b83fd2019-09-18 15:48:23 +020037 RTC_DCHECK_GT(divisor, 0);
38
Danil Chapovalovf4b21da2022-12-20 14:53:35 +000039 if (dividend < Dividend{0}) {
40 auto half_of_divisor = divisor / 2;
41 auto quotient = dividend / divisor;
42 auto remainder = dividend % divisor;
43 if (rtc::SafeGt(-remainder, half_of_divisor)) {
44 --quotient;
45 }
46 return quotient;
47 }
48
Danil Chapovalov33b83fd2019-09-18 15:48:23 +020049 auto half_of_divisor = (divisor - 1) / 2;
50 auto quotient = dividend / divisor;
51 auto remainder = dividend % divisor;
Danil Chapovalovf4b21da2022-12-20 14:53:35 +000052 if (rtc::SafeGt(remainder, half_of_divisor)) {
53 ++quotient;
54 }
55 return quotient;
Danil Chapovalov33b83fd2019-09-18 15:48:23 +020056}
57
58} // namespace webrtc
59
60#endif // RTC_BASE_NUMERICS_DIVIDE_ROUND_H_