1 // Copyright 2021 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef THIRD_PARTY_BASE_CXX17_BACKPORTS_H_
6 #define THIRD_PARTY_BASE_CXX17_BACKPORTS_H_
7
8 #include <stddef.h>
9
10 #include <functional>
11
12 #include "third_party/base/check.h"
13
14 namespace pdfium {
15
16 // C++14 implementation of C++17's std::clamp():
17 // https://en.cppreference.com/w/cpp/algorithm/clamp
18 // Please note that the C++ spec makes it undefined behavior to call std::clamp
19 // with a value of `lo` that compares greater than the value of `hi`. This
20 // implementation uses a CHECK to enforce this as a hard restriction.
21 template <typename T, typename Compare>
clamp(const T & v,const T & lo,const T & hi,Compare comp)22 constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp) {
23 CHECK(!comp(hi, lo));
24 return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
25 }
26
27 template <typename T>
clamp(const T & v,const T & lo,const T & hi)28 constexpr const T& clamp(const T& v, const T& lo, const T& hi) {
29 return pdfium::clamp(v, lo, hi, std::less<T>{});
30 }
31
32 } // namespace pdfium
33
34 #endif // THIRD_PARTY_BASE_CXX17_BACKPORTS_H_
35