From: Joel Rosdahl Date: Thu, 17 Sep 2020 11:23:01 +0000 (+0200) Subject: Add Util::clamp function X-Git-Tag: v4.0~86 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=5618353a316b5614a72bc007e97174e6d82815d7;p=thirdparty%2Fccache.git Add Util::clamp function --- diff --git a/src/Util.hpp b/src/Util.hpp index e14e7f087..01847ecc3 100644 --- a/src/Util.hpp +++ b/src/Util.hpp @@ -25,6 +25,7 @@ #include "third_party/nonstd/optional.hpp" #include "third_party/nonstd/string_view.hpp" +#include #include #include #include @@ -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 +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, diff --git a/src/ccache.cpp b/src/ccache.cpp index bc8778a6d..088c78426 100644 --- a/src/ccache.cpp +++ b/src/ccache.cpp @@ -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]); diff --git a/unittest/test_Util.cpp b/unittest/test_Util.cpp index fab56a444..3c5c49766 100644 --- a/unittest/test_Util.cpp +++ b/unittest/test_Util.cpp @@ -26,6 +26,7 @@ #include +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);