Adds Clamping functions for DataRate.

This is quite useful in many places where we need to restrict the range
of a DataRate. It makes it easier to read the intention than with:
value_ = std::max(some_lower_limit, std::min(value_, some_upper_limit));

The naming follows the naming for rtc::SafeClamp.

Bug: webrtc:9709
Change-Id: I08e05197acec325d85babd2a06806a8667f2fcb1
Reviewed-on: https://webrtc-review.googlesource.com/c/104040
Reviewed-by: Karl Wiberg <kwiberg@webrtc.org>
Commit-Queue: Sebastian Jansson <srte@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#25023}
This commit is contained in:
Sebastian Jansson
2018-10-05 13:23:57 +02:00
committed by Commit Bot
parent b88fe025b7
commit 6c19decc14
2 changed files with 27 additions and 0 deletions

View File

@ -16,6 +16,7 @@
#endif // UNIT_TEST #endif // UNIT_TEST
#include <stdint.h> #include <stdint.h>
#include <algorithm>
#include <cmath> #include <cmath>
#include <limits> #include <limits>
#include <string> #include <string>
@ -133,6 +134,12 @@ class DataRate {
return bits_per_sec_ == data_rate_impl::kPlusInfinityVal; return bits_per_sec_ == data_rate_impl::kPlusInfinityVal;
} }
constexpr bool IsFinite() const { return !IsInfinite(); } constexpr bool IsFinite() const { return !IsInfinite(); }
DataRate Clamped(DataRate min_rate, DataRate max_rate) const {
return std::max(min_rate, std::min(*this, max_rate));
}
void Clamp(DataRate min_rate, DataRate max_rate) {
*this = Clamped(min_rate, max_rate);
}
DataRate operator-(const DataRate& other) const { DataRate operator-(const DataRate& other) const {
return DataRate::bps(bps() - other.bps()); return DataRate::bps(bps() - other.bps());
} }

View File

@ -92,6 +92,26 @@ TEST(DataRateTest, ConvertsToAndFromDouble) {
EXPECT_TRUE(DataRate::bps(kInfinity).IsInfinite()); EXPECT_TRUE(DataRate::bps(kInfinity).IsInfinite());
EXPECT_TRUE(DataRate::kbps(kInfinity).IsInfinite()); EXPECT_TRUE(DataRate::kbps(kInfinity).IsInfinite());
} }
TEST(DataRateTest, Clamping) {
const DataRate upper = DataRate::kbps(800);
const DataRate lower = DataRate::kbps(100);
const DataRate under = DataRate::kbps(100);
const DataRate inside = DataRate::kbps(500);
const DataRate over = DataRate::kbps(1000);
EXPECT_EQ(under.Clamped(lower, upper), lower);
EXPECT_EQ(inside.Clamped(lower, upper), inside);
EXPECT_EQ(over.Clamped(lower, upper), upper);
DataRate mutable_rate = lower;
mutable_rate.Clamp(lower, upper);
EXPECT_EQ(mutable_rate, lower);
mutable_rate = inside;
mutable_rate.Clamp(lower, upper);
EXPECT_EQ(mutable_rate, inside);
mutable_rate = over;
mutable_rate.Clamp(lower, upper);
EXPECT_EQ(mutable_rate, upper);
}
TEST(DataRateTest, MathOperations) { TEST(DataRateTest, MathOperations) {
const int64_t kValueA = 450; const int64_t kValueA = 450;