1 // Copyright 2021 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/cxx17_backports.h"
10 #include <type_traits>
14 #include "base/test/gtest_util.h"
15 #include "testing/gmock/include/gmock/gmock.h"
16 #include "testing/gtest/include/gtest/gtest.h"
25 bool operator<(const OneType& lhs, const OneType& rhs) {
26 return lhs.some_int < rhs.some_int;
29 bool operator==(const OneType& lhs, const OneType& rhs) {
30 return lhs.some_int == rhs.some_int;
37 bool operator==(const AnotherType& lhs, const AnotherType& rhs) {
38 return lhs.some_other_int == rhs.some_other_int;
41 TEST(Cxx17BackportTest, Clamp) {
42 EXPECT_EQ(0, base::clamp(-5, 0, 10));
43 EXPECT_EQ(0, base::clamp(0, 0, 10));
44 EXPECT_EQ(3, base::clamp(3, 0, 10));
45 EXPECT_EQ(10, base::clamp(10, 0, 10));
46 EXPECT_EQ(10, base::clamp(15, 0, 10));
48 EXPECT_EQ(0.0, base::clamp(-5.0, 0.0, 10.0));
49 EXPECT_EQ(0.0, base::clamp(0.0, 0.0, 10.0));
50 EXPECT_EQ(3.0, base::clamp(3.0, 0.0, 10.0));
51 EXPECT_EQ(10.0, base::clamp(10.0, 0.0, 10.0));
52 EXPECT_EQ(10.0, base::clamp(15.0, 0.0, 10.0));
54 EXPECT_EQ(0, base::clamp(-5, 0, 0));
55 EXPECT_EQ(0, base::clamp(0, 0, 0));
56 EXPECT_EQ(0, base::clamp(3, 0, 0));
58 OneType one_type_neg5{-5};
59 OneType one_type_0{0};
60 OneType one_type_3{3};
61 OneType one_type_10{10};
62 OneType one_type_15{15};
64 EXPECT_EQ(one_type_0, base::clamp(one_type_neg5, one_type_0, one_type_10));
65 EXPECT_EQ(one_type_0, base::clamp(one_type_0, one_type_0, one_type_10));
66 EXPECT_EQ(one_type_3, base::clamp(one_type_3, one_type_0, one_type_10));
67 EXPECT_EQ(one_type_10, base::clamp(one_type_10, one_type_0, one_type_10));
68 EXPECT_EQ(one_type_10, base::clamp(one_type_15, one_type_0, one_type_10));
70 AnotherType another_type_neg5{-5};
71 AnotherType another_type_0{0};
72 AnotherType another_type_3{3};
73 AnotherType another_type_10{10};
74 AnotherType another_type_15{15};
76 auto compare_another_type = [](const auto& lhs, const auto& rhs) {
77 return lhs.some_other_int < rhs.some_other_int;
80 EXPECT_EQ(another_type_0, base::clamp(another_type_neg5, another_type_0,
81 another_type_10, compare_another_type));
82 EXPECT_EQ(another_type_0, base::clamp(another_type_0, another_type_0,
83 another_type_10, compare_another_type));
84 EXPECT_EQ(another_type_3, base::clamp(another_type_3, another_type_0,
85 another_type_10, compare_another_type));
86 EXPECT_EQ(another_type_10,
87 base::clamp(another_type_10, another_type_0, another_type_10,
88 compare_another_type));
89 EXPECT_EQ(another_type_10,
90 base::clamp(another_type_15, another_type_0, another_type_10,
91 compare_another_type));
93 EXPECT_CHECK_DEATH(base::clamp(3, 10, 0));
94 EXPECT_CHECK_DEATH(base::clamp(3.0, 10.0, 0.0));
95 EXPECT_CHECK_DEATH(base::clamp(one_type_3, one_type_10, one_type_0));
96 EXPECT_CHECK_DEATH(base::clamp(another_type_3, another_type_10,
97 another_type_0, compare_another_type));