]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Add Util::clamp function
authorJoel Rosdahl <joel@rosdahl.net>
Thu, 17 Sep 2020 11:23:01 +0000 (13:23 +0200)
committerJoel Rosdahl <joel@rosdahl.net>
Thu, 17 Sep 2020 20:17:51 +0000 (22:17 +0200)
src/Util.hpp
src/ccache.cpp
unittest/test_Util.cpp

index e14e7f087f42e62952f7d22a67cfe7bf7e1c341e..01847ecc38cc02e1c6664c4f3f7b53dfae494088 100644 (file)
@@ -25,6 +25,7 @@
 #include "third_party/nonstd/optional.hpp"
 #include "third_party/nonstd/string_view.hpp"
 
+#include <algorithm>
 #include <functional>
 #include <ios>
 #include <memory>
@@ -83,6 +84,14 @@ big_endian_to_int(const uint8_t* buffer, uint8_t& value)
 std::string change_extension(nonstd::string_view path,
                              nonstd::string_view new_ext);
 
+// Return `value` adjusted to not be less than `min` and not more than `max`.
+template<typename T>
+T
+clamp(T value, T min, T max)
+{
+  return std::min(max, std::max(min, value));
+}
+
 // Clone a file from `src` to `dest`. If `via_tmp_file` is true, `src` is cloned
 // to a temporary file and then renamed to `dest`. Throws `Error` on error.
 void clone_file(const std::string& src,
index bc8778a6dac3b9a1a16a67b2d16db658bb641cc9..088c78426cfcb9ff0e0b87e03685a0130cef7192 100644 (file)
@@ -2053,7 +2053,7 @@ do_cache_compilation(Context& ctx, const char* const* argv)
   }
 
   ctx.config.set_limit_multiple(
-    std::min(std::max(ctx.config.limit_multiple(), 0.0), 1.0));
+    Util::clamp(ctx.config.limit_multiple(), 0.0, 1.0));
 
   MTR_BEGIN("main", "guess_compiler");
   ctx.guessed_compiler = guess_compiler(ctx.orig_args[0]);
index fab56a4449461faf7554ad535b04505ecc64b7ba..3c5c497662e5fd016be644b7297e40bba9c86922 100644 (file)
@@ -26,6 +26,7 @@
 
 #include <algorithm>
 
+using doctest::Approx;
 using nonstd::nullopt;
 using TestUtil::TestContext;
 
@@ -93,6 +94,18 @@ TEST_CASE("Util::change_extension")
   CHECK(Util::change_extension("foo.bar.txt", ".o") == "foo.bar.o");
 }
 
+TEST_CASE("Util::clamp")
+{
+  CHECK(Util::clamp(0, 1, 2) == 1);
+  CHECK(Util::clamp(1, 1, 2) == 1);
+  CHECK(Util::clamp(2, 1, 2) == 2);
+  CHECK(Util::clamp(3, 1, 2) == 2);
+
+  CHECK(Util::clamp(7.0, 7.7, 8.8) == Approx(7.7));
+  CHECK(Util::clamp(8.0, 7.7, 8.8) == Approx(8.0));
+  CHECK(Util::clamp(9.0, 7.7, 8.8) == Approx(8.8));
+}
+
 TEST_CASE("Util::common_dir_prefix_length")
 {
   CHECK(Util::common_dir_prefix_length("", "") == 0);