File: integer_division.h

package info (click to toggle)
android-platform-tools 35.0.2-1~exp6
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 211,716 kB
  • sloc: cpp: 995,749; java: 290,495; ansic: 145,647; xml: 58,531; python: 39,608; sh: 14,500; javascript: 5,198; asm: 4,866; makefile: 3,115; yacc: 769; awk: 368; ruby: 183; sql: 140; perl: 88; lex: 67
file content (67 lines) | stat: -rw-r--r-- 2,254 bytes parent folder | download | duplicates (12)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef UTIL_INTEGER_DIVISION_H_
#define UTIL_INTEGER_DIVISION_H_

#include <type_traits>

namespace openscreen {

// Returns CEIL(num รท denom). |denom| must not equal zero. This function is
// compatible with any integer-like type, including the integer-based
// std::chrono duration types.
//
// Optimization note: See DividePositivesRoundingUp().
template <typename Integer>
constexpr auto DivideRoundingUp(Integer num, Integer denom) {
  if (denom < Integer{0}) {
    num *= -1;
    denom *= -1;
  }
  if (num < Integer{0}) {
    return num / denom;
  }
  return (num + denom - Integer{1}) / denom;
}

// Same as DivideRoundingUp(), except is more-efficient for hot code paths that
// know |num| is always greater or equal to zero, and |denom| is always greater
// than zero.
template <typename Integer>
constexpr Integer DividePositivesRoundingUp(Integer num, Integer denom) {
  return DivideRoundingUp<typename std::make_unsigned<Integer>::type>(num,
                                                                      denom);
}

// Divides |num| by |denom|, and rounds to the nearest integer (exactly halfway
// between integers will round to the higher integer). This function is
// compatible with any integer-like type, including the integer-based
// std::chrono duration types.
//
// Optimization note: See DividePositivesRoundingNearest().
template <typename Integer>
constexpr auto DivideRoundingNearest(Integer num, Integer denom) {
  if (denom < Integer{0}) {
    num *= -1;
    denom *= -1;
  }
  if (num < Integer{0}) {
    return (num - ((denom - Integer{1}) / 2)) / denom;
  }
  return (num + (denom / 2)) / denom;
}

// Same as DivideRoundingNearest(), except is more-efficient for hot code paths
// that know |num| is always greater or equal to zero, and |denom| is always
// greater than zero.
template <typename Integer>
constexpr Integer DividePositivesRoundingNearest(Integer num, Integer denom) {
  return DivideRoundingNearest<typename std::make_unsigned<Integer>::type>(
      num, denom);
}

}  // namespace openscreen

#endif  // UTIL_INTEGER_DIVISION_H_