1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef nsAlgorithm_h___
8 #define nsAlgorithm_h___
9 
10 #include <cstdint>
11 #include "mozilla/Assertions.h"
12 
13 template <class T>
NS_ROUNDUP(const T & aA,const T & aB)14 inline T NS_ROUNDUP(const T& aA, const T& aB) {
15   return ((aA + (aB - 1)) / aB) * aB;
16 }
17 
18 // We use these instead of std::min/max because we can't include the algorithm
19 // header in all of XPCOM because the stl wrappers will error out when included
20 // in parts of XPCOM. These functions should never be used outside of XPCOM.
21 template <class T>
XPCOM_MIN(const T & aA,const T & aB)22 inline const T& XPCOM_MIN(const T& aA, const T& aB) {
23   return aB < aA ? aB : aA;
24 }
25 
26 // Must return b when a == b in case a is -0
27 template <class T>
XPCOM_MAX(const T & aA,const T & aB)28 inline const T& XPCOM_MAX(const T& aA, const T& aB) {
29   return aA > aB ? aA : aB;
30 }
31 
32 namespace mozilla {
33 
34 template <class T>
clamped(const T & aA,const T & aMin,const T & aMax)35 inline const T& clamped(const T& aA, const T& aMin, const T& aMax) {
36   MOZ_ASSERT(aMax >= aMin,
37              "clamped(): aMax must be greater than or equal to aMin");
38   return XPCOM_MIN(XPCOM_MAX(aA, aMin), aMax);
39 }
40 
41 }  // namespace mozilla
42 
43 template <class InputIterator, class T>
NS_COUNT(InputIterator & aFirst,const InputIterator & aLast,const T & aValue)44 inline uint32_t NS_COUNT(InputIterator& aFirst, const InputIterator& aLast,
45                          const T& aValue) {
46   uint32_t result = 0;
47   for (; aFirst != aLast; ++aFirst)
48     if (*aFirst == aValue) {
49       ++result;
50     }
51   return result;
52 }
53 
54 #endif  // !defined(nsAlgorithm_h___)
55