2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <type_traits>
23 // TLDR: Prefer using operator< for ordering. And when
24 // a and b are equivalent objects, we return b to make
26 // See http://stepanovpapers.com/notes.pdf for details.
28 constexpr T constexpr_max(T a) {
31 template <typename T, typename... Ts>
32 constexpr T constexpr_max(T a, T b, Ts... ts) {
33 return b < a ? constexpr_max(a, ts...) : constexpr_max(b, ts...);
36 // When a and b are equivalent objects, we return a to
37 // make sorting stable.
39 constexpr T constexpr_min(T a) {
42 template <typename T, typename... Ts>
43 constexpr T constexpr_min(T a, T b, Ts... ts) {
44 return b < a ? constexpr_min(b, ts...) : constexpr_min(a, ts...);
49 template <typename T, typename = void>
50 struct constexpr_abs_helper {};
53 struct constexpr_abs_helper<
55 typename std::enable_if<std::is_floating_point<T>::value>::type> {
56 static constexpr T go(T t) {
57 return t < static_cast<T>(0) ? -t : t;
62 struct constexpr_abs_helper<
64 typename std::enable_if<
65 std::is_integral<T>::value && !std::is_same<T, bool>::value &&
66 std::is_unsigned<T>::value>::type> {
67 static constexpr T go(T t) {
73 struct constexpr_abs_helper<
75 typename std::enable_if<
76 std::is_integral<T>::value && !std::is_same<T, bool>::value &&
77 std::is_signed<T>::value>::type> {
78 static constexpr typename std::make_unsigned<T>::type go(T t) {
79 return typename std::make_unsigned<T>::type(t < static_cast<T>(0) ? -t : t);
85 constexpr auto constexpr_abs(T t)
86 -> decltype(detail::constexpr_abs_helper<T>::go(t)) {
87 return detail::constexpr_abs_helper<T>::go(t);
92 constexpr T constexpr_log2(T a, T e) {
93 return e == T(1) ? a : constexpr_log2(a + T(1), e / T(2));
98 constexpr T constexpr_log2(T t) {
99 return detail::constexpr_log2(T(0), t);