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/. */
8 * Reusable template meta-functions on types and compile-time values. Meta-
9 * functions are placed inside the 'tl' namespace to avoid conflict with non-
10 * meta functions of the same name (e.g., mozilla::tl::FloorLog2 vs.
11 * mozilla::FloorLog2).
13 * When constexpr support becomes universal, we should probably use that instead
14 * of some of these templates, for simplicity.
17 #ifndef mozilla_TemplateLib_h
18 #define mozilla_TemplateLib_h
27 /** Compute min/max. */
28 template<size_t I
, size_t J
>
31 static const size_t value
= I
< J
? I
: J
;
33 template<size_t I
, size_t J
>
36 static const size_t value
= I
> J
? I
: J
;
39 /** Compute floor(log2(i)). */
43 static const size_t value
= 1 + FloorLog2
<I
/ 2>::value
;
45 template<> struct FloorLog2
<0> { /* Error */ };
46 template<> struct FloorLog2
<1> { static const size_t value
= 0; };
48 /** Compute ceiling(log2(i)). */
52 static const size_t value
= FloorLog2
<2 * I
- 1>::value
;
55 /** Round up to the nearest power of 2. */
59 static const size_t value
= size_t(1) << CeilingLog2
<I
>::value
;
64 static const size_t value
= 1;
67 /** Compute the number of bits in the given unsigned type. */
71 static const size_t value
= sizeof(T
) * CHAR_BIT
;
75 * Produce an N-bit mask, where N <= BitSize<size_t>::value. Handle the
76 * language-undefined edge case when N = BitSize<size_t>::value.
81 // Assert the precondition. On success this evaluates to 0. Otherwise it
82 // triggers divide-by-zero at compile time: a guaranteed compile error in
83 // C++11, and usually one in C++98. Add this value to |value| to assure
85 static const size_t checkPrecondition
=
86 0 / size_t(N
< BitSize
<size_t>::value
);
87 static const size_t value
= (size_t(1) << N
) - 1 + checkPrecondition
;
90 struct NBitMask
<BitSize
<size_t>::value
>
92 static const size_t value
= size_t(-1);
96 * For the unsigned integral type size_t, compute a mask M for N such that
97 * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t)
100 struct MulOverflowMask
102 static const size_t value
=
103 ~NBitMask
<BitSize
<size_t>::value
- CeilingLog2
<N
>::value
>::value
;
105 template<> struct MulOverflowMask
<0> { /* Error */ };
106 template<> struct MulOverflowMask
<1> { static const size_t value
= 0; };
110 } // namespace mozilla
112 #endif /* mozilla_TemplateLib_h */