Adds shared base class for data units.

This reduces code duplication and ensures common behavior
between the unit classes.

Bug: webrtc:9709
Change-Id: I9529ef10b3f538355f53250a2b67c6b4e250cce8
Reviewed-on: https://webrtc-review.googlesource.com/c/110901
Commit-Queue: Sebastian Jansson <srte@webrtc.org>
Reviewed-by: Karl Wiberg <kwiberg@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#25690}
This commit is contained in:
Sebastian Jansson
2018-11-19 11:17:12 +01:00
committed by Commit Bot
parent d474672dcd
commit 72bba625d5
14 changed files with 697 additions and 678 deletions

View File

@ -43,6 +43,7 @@ specific_include_rules = {
".*\.h": [
"+rtc_base/checks.h",
"+rtc_base/system/rtc_export.h",
"+rtc_base/units/unit_base.h",
],
"array_view\.h": [
@ -252,22 +253,6 @@ specific_include_rules = {
"+modules/video_coding/include/video_codec_interface.h"
],
"data_rate\.h": [
"+rtc_base/numerics/safe_conversions.h",
],
"data_size\.h": [
"+rtc_base/numerics/safe_conversions.h",
],
"time_delta\.h": [
"+rtc_base/numerics/safe_conversions.h",
],
"timestamp\.h": [
"+rtc_base/numerics/safe_conversions.h",
],
"i010_buffer\.h": [
"+rtc_base/memory/aligned_malloc.h"
],

View File

@ -19,8 +19,8 @@ rtc_source_set("data_rate") {
":data_size",
":time_delta",
"../../rtc_base:checks",
"../../rtc_base:safe_conversions",
"../../rtc_base:stringutils",
"../../rtc_base/units:unit_base",
]
}
@ -33,8 +33,8 @@ rtc_source_set("data_size") {
deps = [
"../../rtc_base:checks",
"../../rtc_base:safe_conversions",
"../../rtc_base:stringutils",
"../../rtc_base/units:unit_base",
]
}
@ -47,8 +47,8 @@ rtc_source_set("time_delta") {
deps = [
"../../rtc_base:checks",
"../../rtc_base:safe_conversions",
"../../rtc_base:stringutils",
"../../rtc_base/units:unit_base",
]
}
@ -62,8 +62,8 @@ rtc_source_set("timestamp") {
deps = [
":time_delta",
"../../rtc_base:checks",
"../../rtc_base:safe_conversions",
"../../rtc_base:stringutils",
"../../rtc_base/units:unit_base",
]
}

View File

@ -14,7 +14,7 @@
namespace webrtc {
std::string ToString(const DataRate& value) {
std::string ToString(DataRate value) {
char buf[64];
rtc::SimpleStringBuilder sb(buf);
if (value.IsInfinite()) {

View File

@ -15,9 +15,6 @@
#include <ostream> // no-presubmit-check TODO(webrtc:8982)
#endif // UNIT_TEST
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <string>
#include <type_traits>
@ -25,12 +22,10 @@
#include "api/units/data_size.h"
#include "api/units/time_delta.h"
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_conversions.h"
#include "rtc_base/units/unit_base.h"
namespace webrtc {
namespace data_rate_impl {
constexpr int64_t kPlusInfinityVal = std::numeric_limits<int64_t>::max();
inline int64_t Microbits(const DataSize& size) {
constexpr int64_t kMaxBeforeConversion =
std::numeric_limits<int64_t>::max() / 8000000;
@ -43,191 +38,64 @@ inline int64_t Microbits(const DataSize& size) {
// DataRate is a class that represents a given data rate. This can be used to
// represent bandwidth, encoding bitrate, etc. The internal storage is bits per
// second (bps).
class DataRate {
class DataRate final : public rtc_units_impl::RelativeUnit<DataRate> {
public:
DataRate() = delete;
static constexpr DataRate Zero() { return DataRate(0); }
static constexpr DataRate Infinity() {
return DataRate(data_rate_impl::kPlusInfinityVal);
}
static constexpr DataRate Infinity() { return PlusInfinity(); }
template <int64_t bps>
static constexpr DataRate BitsPerSec() {
static_assert(bps >= 0, "");
static_assert(bps < data_rate_impl::kPlusInfinityVal, "");
return DataRate(bps);
return FromStaticValue<bps>();
}
template <int64_t kbps>
static constexpr DataRate KilobitsPerSec() {
static_assert(kbps >= 0, "");
static_assert(kbps < data_rate_impl::kPlusInfinityVal / 1000, "");
return DataRate(kbps * 1000);
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
static DataRate bps(T bits_per_second) {
RTC_DCHECK_GE(bits_per_second, 0);
RTC_DCHECK_LT(bits_per_second, data_rate_impl::kPlusInfinityVal);
return DataRate(rtc::dchecked_cast<int64_t>(bits_per_second));
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
static DataRate kbps(T kilobits_per_sec) {
RTC_DCHECK_GE(kilobits_per_sec, 0);
RTC_DCHECK_LT(kilobits_per_sec, data_rate_impl::kPlusInfinityVal / 1000);
return DataRate::bps(rtc::dchecked_cast<int64_t>(kilobits_per_sec) * 1000);
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static DataRate bps(T bits_per_second) {
if (bits_per_second == std::numeric_limits<T>::infinity()) {
return Infinity();
} else {
RTC_DCHECK(!std::isnan(bits_per_second));
RTC_DCHECK_GE(bits_per_second, 0);
RTC_DCHECK_LT(bits_per_second, data_rate_impl::kPlusInfinityVal);
return DataRate(rtc::dchecked_cast<int64_t>(bits_per_second));
}
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static DataRate kbps(T kilobits_per_sec) {
return DataRate::bps(kilobits_per_sec * 1e3);
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type bps() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(bits_per_sec_);
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type kbps() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(UnsafeKilobitsPerSec());
}
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value,
T>::type constexpr bps() const {
return IsInfinite() ? std::numeric_limits<T>::infinity() : bits_per_sec_;
return FromStaticFraction<kbps, 1000>();
}
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value,
T>::type constexpr kbps() const {
return bps<T>() * 1e-3;
static constexpr DataRate bps(T bits_per_second) {
return FromValue(bits_per_second);
}
template <typename T>
static constexpr DataRate kbps(T kilobits_per_sec) {
return FromFraction<1000>(kilobits_per_sec);
}
template <typename T = int64_t>
constexpr T bps() const {
return ToValue<T>();
}
template <typename T = int64_t>
T kbps() const {
return ToFraction<1000, T>();
}
constexpr int64_t bps_or(int64_t fallback_value) const {
return IsFinite() ? bits_per_sec_ : fallback_value;
return ToValueOr(fallback_value);
}
constexpr int64_t kbps_or(int64_t fallback_value) const {
return IsFinite() ? UnsafeKilobitsPerSec() : fallback_value;
}
constexpr bool IsZero() const { return bits_per_sec_ == 0; }
constexpr bool IsInfinite() const {
return bits_per_sec_ == data_rate_impl::kPlusInfinityVal;
}
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 {
return DataRate::bps(bps() - other.bps());
}
DataRate operator+(const DataRate& other) const {
return DataRate::bps(bps() + other.bps());
}
DataRate& operator-=(const DataRate& other) {
*this = *this - other;
return *this;
}
DataRate& operator+=(const DataRate& other) {
*this = *this + other;
return *this;
}
constexpr double operator/(const DataRate& other) const {
return bps<double>() / other.bps<double>();
}
constexpr bool operator==(const DataRate& other) const {
return bits_per_sec_ == other.bits_per_sec_;
}
constexpr bool operator!=(const DataRate& other) const {
return bits_per_sec_ != other.bits_per_sec_;
}
constexpr bool operator<=(const DataRate& other) const {
return bits_per_sec_ <= other.bits_per_sec_;
}
constexpr bool operator>=(const DataRate& other) const {
return bits_per_sec_ >= other.bits_per_sec_;
}
constexpr bool operator>(const DataRate& other) const {
return bits_per_sec_ > other.bits_per_sec_;
}
constexpr bool operator<(const DataRate& other) const {
return bits_per_sec_ < other.bits_per_sec_;
return ToFractionOr<1000>(fallback_value);
}
private:
// Bits per second used internally to simplify debugging by making the value
// more recognizable.
explicit constexpr DataRate(int64_t bits_per_second)
: bits_per_sec_(bits_per_second) {}
constexpr int64_t UnsafeKilobitsPerSec() const {
return (bits_per_sec_ + 500) / 1000;
}
int64_t bits_per_sec_;
friend class rtc_units_impl::UnitBase<DataRate>;
using RelativeUnit::RelativeUnit;
static constexpr bool one_sided = true;
};
inline DataRate operator*(const DataRate& rate, const double& scalar) {
return DataRate::bps(std::round(rate.bps() * scalar));
}
inline DataRate operator*(const double& scalar, const DataRate& rate) {
return rate * scalar;
}
inline DataRate operator*(const DataRate& rate, const int64_t& scalar) {
return DataRate::bps(rate.bps() * scalar);
}
inline DataRate operator*(const int64_t& scalar, const DataRate& rate) {
return rate * scalar;
}
inline DataRate operator*(const DataRate& rate, const int32_t& scalar) {
return DataRate::bps(rate.bps() * scalar);
}
inline DataRate operator*(const int32_t& scalar, const DataRate& rate) {
return rate * scalar;
}
template <typename T>
typename std::enable_if<std::is_arithmetic<T>::value, DataRate>::type operator/(
const DataRate& rate,
const T& scalar) {
return DataRate::bps(rate.bps<double>() / scalar);
}
inline DataRate operator/(const DataSize& size, const TimeDelta& duration) {
inline DataRate operator/(const DataSize size, const TimeDelta duration) {
return DataRate::bps(data_rate_impl::Microbits(size) / duration.us());
}
inline TimeDelta operator/(const DataSize& size, const DataRate& rate) {
inline TimeDelta operator/(const DataSize size, const DataRate rate) {
return TimeDelta::us(data_rate_impl::Microbits(size) / rate.bps());
}
inline DataSize operator*(const DataRate& rate, const TimeDelta& duration) {
inline DataSize operator*(const DataRate rate, const TimeDelta duration) {
int64_t microbits = rate.bps() * duration.us();
return DataSize::bytes((microbits + 4000000) / 8000000);
}
inline DataSize operator*(const TimeDelta& duration, const DataRate& rate) {
inline DataSize operator*(const TimeDelta duration, const DataRate rate) {
return rate * duration;
}
std::string ToString(const DataRate& value);
std::string ToString(DataRate value);
#ifdef UNIT_TEST
inline std::ostream& operator<<( // no-presubmit-check TODO(webrtc:8982)

View File

@ -14,7 +14,7 @@
namespace webrtc {
std::string ToString(const DataSize& value) {
std::string ToString(DataSize value) {
char buf[64];
rtc::SimpleStringBuilder sb(buf);
if (value.IsInfinite()) {

View File

@ -15,143 +15,44 @@
#include <ostream> // no-presubmit-check TODO(webrtc:8982)
#endif // UNIT_TEST
#include <stdint.h>
#include <cmath>
#include <limits>
#include <string>
#include <type_traits>
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_conversions.h"
#include "rtc_base/units/unit_base.h"
namespace webrtc {
namespace data_size_impl {
constexpr int64_t kPlusInfinityVal = std::numeric_limits<int64_t>::max();
} // namespace data_size_impl
// DataSize is a class represeting a count of bytes.
class DataSize {
class DataSize final : public rtc_units_impl::RelativeUnit<DataSize> {
public:
DataSize() = delete;
static constexpr DataSize Zero() { return DataSize(0); }
static constexpr DataSize Infinity() {
return DataSize(data_size_impl::kPlusInfinityVal);
}
static constexpr DataSize Infinity() { return PlusInfinity(); }
template <int64_t bytes>
static constexpr DataSize Bytes() {
static_assert(bytes >= 0, "");
static_assert(bytes < data_size_impl::kPlusInfinityVal, "");
return DataSize(bytes);
return FromStaticValue<bytes>();
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
static DataSize bytes(T bytes) {
RTC_DCHECK_GE(bytes, 0);
RTC_DCHECK_LT(bytes, data_size_impl::kPlusInfinityVal);
return DataSize(rtc::dchecked_cast<int64_t>(bytes));
return FromValue(bytes);
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static DataSize bytes(T bytes) {
if (bytes == std::numeric_limits<T>::infinity()) {
return Infinity();
} else {
RTC_DCHECK(!std::isnan(bytes));
RTC_DCHECK_GE(bytes, 0);
RTC_DCHECK_LT(bytes, data_size_impl::kPlusInfinityVal);
return DataSize(rtc::dchecked_cast<int64_t>(bytes));
}
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type bytes() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(bytes_);
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
bytes() const {
return IsInfinite() ? std::numeric_limits<T>::infinity() : bytes_;
typename std::enable_if<std::is_arithmetic<T>::value, T>::type bytes() const {
return ToValue<T>();
}
constexpr int64_t bytes_or(int64_t fallback_value) const {
return IsFinite() ? bytes_ : fallback_value;
}
constexpr bool IsZero() const { return bytes_ == 0; }
constexpr bool IsInfinite() const {
return bytes_ == data_size_impl::kPlusInfinityVal;
}
constexpr bool IsFinite() const { return !IsInfinite(); }
DataSize operator-(const DataSize& other) const {
return DataSize::bytes(bytes() - other.bytes());
}
DataSize operator+(const DataSize& other) const {
return DataSize::bytes(bytes() + other.bytes());
}
DataSize& operator-=(const DataSize& other) {
*this = *this - other;
return *this;
}
DataSize& operator+=(const DataSize& other) {
*this = *this + other;
return *this;
}
constexpr double operator/(const DataSize& other) const {
return bytes<double>() / other.bytes<double>();
}
constexpr bool operator==(const DataSize& other) const {
return bytes_ == other.bytes_;
}
constexpr bool operator!=(const DataSize& other) const {
return bytes_ != other.bytes_;
}
constexpr bool operator<=(const DataSize& other) const {
return bytes_ <= other.bytes_;
}
constexpr bool operator>=(const DataSize& other) const {
return bytes_ >= other.bytes_;
}
constexpr bool operator>(const DataSize& other) const {
return bytes_ > other.bytes_;
}
constexpr bool operator<(const DataSize& other) const {
return bytes_ < other.bytes_;
return ToValueOr(fallback_value);
}
private:
explicit constexpr DataSize(int64_t bytes) : bytes_(bytes) {}
int64_t bytes_;
friend class rtc_units_impl::UnitBase<DataSize>;
using RelativeUnit::RelativeUnit;
static constexpr bool one_sided = true;
};
inline DataSize operator*(const DataSize& size, const double& scalar) {
return DataSize::bytes(std::round(size.bytes() * scalar));
}
inline DataSize operator*(const double& scalar, const DataSize& size) {
return size * scalar;
}
inline DataSize operator*(const DataSize& size, const int64_t& scalar) {
return DataSize::bytes(size.bytes() * scalar);
}
inline DataSize operator*(const int64_t& scalar, const DataSize& size) {
return size * scalar;
}
inline DataSize operator*(const DataSize& size, const int32_t& scalar) {
return DataSize::bytes(size.bytes() * scalar);
}
inline DataSize operator*(const int32_t& scalar, const DataSize& size) {
return size * scalar;
}
inline DataSize operator/(const DataSize& size, const int64_t& scalar) {
return DataSize::bytes(size.bytes() / scalar);
}
std::string ToString(const DataSize& value);
std::string ToString(DataSize value);
#ifdef UNIT_TEST
inline std::ostream& operator<<( // no-presubmit-check TODO(webrtc:8982)

View File

@ -14,7 +14,7 @@
namespace webrtc {
std::string ToString(const TimeDelta& value) {
std::string ToString(TimeDelta value) {
char buf[64];
rtc::SimpleStringBuilder sb(buf);
if (value.IsPlusInfinity()) {

View File

@ -15,23 +15,13 @@
#include <ostream> // no-presubmit-check TODO(webrtc:8982)
#endif // UNIT_TEST
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <string>
#include <type_traits>
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_conversions.h"
#include "rtc_base/units/unit_base.h"
namespace webrtc {
namespace timedelta_impl {
constexpr int64_t kPlusInfinityVal = std::numeric_limits<int64_t>::max();
constexpr int64_t kMinusInfinityVal = std::numeric_limits<int64_t>::min();
} // namespace timedelta_impl
// TimeDelta represents the difference between two timestamps. Commonly this can
// be a duration. However since two Timestamps are not guaranteed to have the
// same epoch (they might come from different computers, making exact
@ -39,251 +29,69 @@ constexpr int64_t kMinusInfinityVal = std::numeric_limits<int64_t>::min();
// undefined. To simplify usage, it can be constructed and converted to
// different units, specifically seconds (s), milliseconds (ms) and
// microseconds (us).
class TimeDelta {
class TimeDelta final : public rtc_units_impl::RelativeUnit<TimeDelta> {
public:
TimeDelta() = delete;
static constexpr TimeDelta Zero() { return TimeDelta(0); }
static constexpr TimeDelta PlusInfinity() {
return TimeDelta(timedelta_impl::kPlusInfinityVal);
}
static constexpr TimeDelta MinusInfinity() {
return TimeDelta(timedelta_impl::kMinusInfinityVal);
}
template <int64_t seconds>
static constexpr TimeDelta Seconds() {
static_assert(seconds > timedelta_impl::kMinusInfinityVal / 1000000, "");
static_assert(seconds < timedelta_impl::kPlusInfinityVal / 1000000, "");
return TimeDelta(seconds * 1000000);
return FromStaticFraction<seconds, 1000000>();
}
template <int64_t ms>
static constexpr TimeDelta Millis() {
static_assert(ms > timedelta_impl::kMinusInfinityVal / 1000, "");
static_assert(ms < timedelta_impl::kPlusInfinityVal / 1000, "");
return TimeDelta(ms * 1000);
return FromStaticFraction<ms, 1000>();
}
template <int64_t us>
static constexpr TimeDelta Micros() {
static_assert(us > timedelta_impl::kMinusInfinityVal, "");
static_assert(us < timedelta_impl::kPlusInfinityVal, "");
return TimeDelta(us);
return FromStaticValue<us>();
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
template <typename T>
static TimeDelta seconds(T seconds) {
RTC_DCHECK_GT(seconds, timedelta_impl::kMinusInfinityVal / 1000000);
RTC_DCHECK_LT(seconds, timedelta_impl::kPlusInfinityVal / 1000000);
return TimeDelta(rtc::dchecked_cast<int64_t>(seconds) * 1000000);
return FromFraction<1000000>(seconds);
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
template <typename T>
static TimeDelta ms(T milliseconds) {
RTC_DCHECK_GT(milliseconds, timedelta_impl::kMinusInfinityVal / 1000);
RTC_DCHECK_LT(milliseconds, timedelta_impl::kPlusInfinityVal / 1000);
return TimeDelta(rtc::dchecked_cast<int64_t>(milliseconds) * 1000);
return FromFraction<1000>(milliseconds);
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
template <typename T>
static TimeDelta us(T microseconds) {
RTC_DCHECK_GT(microseconds, timedelta_impl::kMinusInfinityVal);
RTC_DCHECK_LT(microseconds, timedelta_impl::kPlusInfinityVal);
return TimeDelta(rtc::dchecked_cast<int64_t>(microseconds));
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static TimeDelta seconds(T seconds) {
return TimeDelta::us(seconds * 1e6);
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static TimeDelta ms(T milliseconds) {
return TimeDelta::us(milliseconds * 1e3);
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static TimeDelta us(T microseconds) {
if (microseconds == std::numeric_limits<T>::infinity()) {
return PlusInfinity();
} else if (microseconds == -std::numeric_limits<T>::infinity()) {
return MinusInfinity();
} else {
RTC_DCHECK(!std::isnan(microseconds));
RTC_DCHECK_GT(microseconds, timedelta_impl::kMinusInfinityVal);
RTC_DCHECK_LT(microseconds, timedelta_impl::kPlusInfinityVal);
return TimeDelta(rtc::dchecked_cast<int64_t>(microseconds));
}
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type seconds() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(UnsafeSeconds());
return FromValue(microseconds);
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type ms() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(UnsafeMillis());
T seconds() const {
return ToFraction<1000000, T>();
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type us() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(microseconds_);
T ms() const {
return ToFraction<1000, T>();
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type ns() const {
RTC_DCHECK_GE(us(), std::numeric_limits<T>::min() / 1000);
RTC_DCHECK_LE(us(), std::numeric_limits<T>::max() / 1000);
return rtc::dchecked_cast<T>(us() * 1000);
T us() const {
return ToValue<T>();
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
seconds() const {
return us<T>() * 1e-6;
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
ms() const {
return us<T>() * 1e-3;
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
us() const {
return IsPlusInfinity()
? std::numeric_limits<T>::infinity()
: IsMinusInfinity() ? -std::numeric_limits<T>::infinity()
: microseconds_;
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
ns() const {
return us<T>() * 1e3;
template <typename T = int64_t>
T ns() const {
return ToMultiple<1000, T>();
}
constexpr int64_t seconds_or(int64_t fallback_value) const {
return IsFinite() ? UnsafeSeconds() : fallback_value;
return ToFractionOr<1000000>(fallback_value);
}
constexpr int64_t ms_or(int64_t fallback_value) const {
return IsFinite() ? UnsafeMillis() : fallback_value;
return ToFractionOr<1000>(fallback_value);
}
constexpr int64_t us_or(int64_t fallback_value) const {
return IsFinite() ? microseconds_ : fallback_value;
return ToValueOr(fallback_value);
}
TimeDelta Abs() const { return TimeDelta::us(std::abs(us())); }
constexpr bool IsZero() const { return microseconds_ == 0; }
constexpr bool IsFinite() const { return !IsInfinite(); }
constexpr bool IsInfinite() const {
return microseconds_ == timedelta_impl::kPlusInfinityVal ||
microseconds_ == timedelta_impl::kMinusInfinityVal;
}
constexpr bool IsPlusInfinity() const {
return microseconds_ == timedelta_impl::kPlusInfinityVal;
}
constexpr bool IsMinusInfinity() const {
return microseconds_ == timedelta_impl::kMinusInfinityVal;
}
TimeDelta Clamped(TimeDelta min_delta, TimeDelta max_delta) const {
return std::max(min_delta, std::min(*this, max_delta));
}
void Clamp(TimeDelta min_delta, TimeDelta max_delta) {
*this = Clamped(min_delta, max_delta);
}
TimeDelta operator+(const TimeDelta& other) const {
if (IsPlusInfinity() || other.IsPlusInfinity()) {
RTC_DCHECK(!IsMinusInfinity());
RTC_DCHECK(!other.IsMinusInfinity());
return PlusInfinity();
} else if (IsMinusInfinity() || other.IsMinusInfinity()) {
RTC_DCHECK(!IsPlusInfinity());
RTC_DCHECK(!other.IsPlusInfinity());
return MinusInfinity();
}
return TimeDelta::us(us() + other.us());
}
TimeDelta operator-(const TimeDelta& other) const {
if (IsPlusInfinity() || other.IsMinusInfinity()) {
RTC_DCHECK(!IsMinusInfinity());
RTC_DCHECK(!other.IsPlusInfinity());
return PlusInfinity();
} else if (IsMinusInfinity() || other.IsPlusInfinity()) {
RTC_DCHECK(!IsPlusInfinity());
RTC_DCHECK(!other.IsMinusInfinity());
return MinusInfinity();
}
return TimeDelta::us(us() - other.us());
}
TimeDelta& operator-=(const TimeDelta& other) {
*this = *this - other;
return *this;
}
TimeDelta& operator+=(const TimeDelta& other) {
*this = *this + other;
return *this;
}
constexpr double operator/(const TimeDelta& other) const {
return us<double>() / other.us<double>();
}
constexpr bool operator==(const TimeDelta& other) const {
return microseconds_ == other.microseconds_;
}
constexpr bool operator!=(const TimeDelta& other) const {
return microseconds_ != other.microseconds_;
}
constexpr bool operator<=(const TimeDelta& other) const {
return microseconds_ <= other.microseconds_;
}
constexpr bool operator>=(const TimeDelta& other) const {
return microseconds_ >= other.microseconds_;
}
constexpr bool operator>(const TimeDelta& other) const {
return microseconds_ > other.microseconds_;
}
constexpr bool operator<(const TimeDelta& other) const {
return microseconds_ < other.microseconds_;
}
private:
explicit constexpr TimeDelta(int64_t us) : microseconds_(us) {}
constexpr int64_t UnsafeSeconds() const {
return (microseconds_ + (microseconds_ >= 0 ? 500000 : -500000)) / 1000000;
}
constexpr int64_t UnsafeMillis() const {
return (microseconds_ + (microseconds_ >= 0 ? 500 : -500)) / 1000;
}
int64_t microseconds_;
friend class rtc_units_impl::UnitBase<TimeDelta>;
using RelativeUnit::RelativeUnit;
static constexpr bool one_sided = false;
};
inline TimeDelta operator*(const TimeDelta& delta, const double& scalar) {
return TimeDelta::us(std::round(delta.us() * scalar));
}
inline TimeDelta operator*(const double& scalar, const TimeDelta& delta) {
return delta * scalar;
}
inline TimeDelta operator*(const TimeDelta& delta, const int64_t& scalar) {
return TimeDelta::us(delta.us() * scalar);
}
inline TimeDelta operator*(const int64_t& scalar, const TimeDelta& delta) {
return delta * scalar;
}
inline TimeDelta operator*(const TimeDelta& delta, const int32_t& scalar) {
return TimeDelta::us(delta.us() * scalar);
}
inline TimeDelta operator*(const int32_t& scalar, const TimeDelta& delta) {
return delta * scalar;
}
inline TimeDelta operator/(const TimeDelta& delta, const int64_t& scalar) {
return TimeDelta::us(delta.us() / scalar);
}
std::string ToString(const TimeDelta& value);
std::string ToString(TimeDelta value);
#ifdef UNIT_TEST
inline std::ostream& operator<<( // no-presubmit-check TODO(webrtc:8982)

View File

@ -10,6 +10,8 @@
#include "api/units/time_delta.h"
#include <limits>
#include "test/gtest.h"
namespace webrtc {

View File

@ -13,7 +13,7 @@
#include "rtc_base/strings/string_builder.h"
namespace webrtc {
std::string ToString(const Timestamp& value) {
std::string ToString(Timestamp value) {
char buf[64];
rtc::SimpleStringBuilder sb(buf);
if (value.IsInfinite()) {

View File

@ -15,191 +15,94 @@
#include <ostream> // no-presubmit-check TODO(webrtc:8982)
#endif // UNIT_TEST
#include <math.h>
#include <stdint.h>
#include <limits>
#include <string>
#include <type_traits>
#include "api/units/time_delta.h"
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_conversions.h"
namespace webrtc {
namespace timestamp_impl {
constexpr int64_t kPlusInfinityVal = std::numeric_limits<int64_t>::max();
constexpr int64_t kMinusInfinityVal = std::numeric_limits<int64_t>::min();
} // namespace timestamp_impl
// Timestamp represents the time that has passed since some unspecified epoch.
// The epoch is assumed to be before any represented timestamps, this means that
// negative values are not valid. The most notable feature is that the
// difference of two Timestamps results in a TimeDelta.
class Timestamp {
class Timestamp final : public rtc_units_impl::UnitBase<Timestamp> {
public:
Timestamp() = delete;
static constexpr Timestamp PlusInfinity() {
return Timestamp(timestamp_impl::kPlusInfinityVal);
}
static constexpr Timestamp MinusInfinity() {
return Timestamp(timestamp_impl::kMinusInfinityVal);
}
template <int64_t seconds>
static constexpr Timestamp Seconds() {
static_assert(seconds >= 0, "");
static_assert(seconds < timestamp_impl::kPlusInfinityVal / 1000000, "");
return Timestamp(seconds * 1000000);
return FromStaticFraction<seconds, 1000000>();
}
template <int64_t ms>
static constexpr Timestamp Millis() {
static_assert(ms >= 0, "");
static_assert(ms < timestamp_impl::kPlusInfinityVal / 1000, "");
return Timestamp(ms * 1000);
return FromStaticFraction<ms, 1000>();
}
template <int64_t us>
static constexpr Timestamp Micros() {
static_assert(us >= 0, "");
static_assert(us < timestamp_impl::kPlusInfinityVal, "");
return Timestamp(us);
return FromStaticValue<us>();
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
template <typename T>
static Timestamp seconds(T seconds) {
RTC_DCHECK_GE(seconds, 0);
RTC_DCHECK_LT(seconds, timestamp_impl::kPlusInfinityVal / 1000000);
return Timestamp(rtc::dchecked_cast<int64_t>(seconds) * 1000000);
return FromFraction<1000000>(seconds);
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
template <typename T>
static Timestamp ms(T milliseconds) {
RTC_DCHECK_GE(milliseconds, 0);
RTC_DCHECK_LT(milliseconds, timestamp_impl::kPlusInfinityVal / 1000);
return Timestamp(rtc::dchecked_cast<int64_t>(milliseconds) * 1000);
return FromFraction<1000>(milliseconds);
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
template <typename T>
static Timestamp us(T microseconds) {
RTC_DCHECK_GE(microseconds, 0);
RTC_DCHECK_LT(microseconds, timestamp_impl::kPlusInfinityVal);
return Timestamp(rtc::dchecked_cast<int64_t>(microseconds));
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static Timestamp seconds(T seconds) {
return Timestamp::us(seconds * 1e6);
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static Timestamp ms(T milliseconds) {
return Timestamp::us(milliseconds * 1e3);
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static Timestamp us(T microseconds) {
if (microseconds == std::numeric_limits<double>::infinity()) {
return PlusInfinity();
} else if (microseconds == -std::numeric_limits<double>::infinity()) {
return MinusInfinity();
} else {
RTC_DCHECK(!std::isnan(microseconds));
RTC_DCHECK_GE(microseconds, 0);
RTC_DCHECK_LT(microseconds, timestamp_impl::kPlusInfinityVal);
return Timestamp(rtc::dchecked_cast<int64_t>(microseconds));
}
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type seconds() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(UnsafeSeconds());
return FromValue(microseconds);
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type ms() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(UnsafeMillis());
T seconds() const {
return ToFraction<1000000, T>();
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type us() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(microseconds_);
T ms() const {
return ToFraction<1000, T>();
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
seconds() const {
return us<T>() * 1e-6;
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
ms() const {
return us<T>() * 1e-3;
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
us() const {
return IsPlusInfinity()
? std::numeric_limits<T>::infinity()
: IsMinusInfinity() ? -std::numeric_limits<T>::infinity()
: microseconds_;
template <typename T = int64_t>
T us() const {
return ToValue<T>();
}
constexpr int64_t seconds_or(int64_t fallback_value) const {
return IsFinite() ? UnsafeSeconds() : fallback_value;
return ToFractionOr<1000000>(fallback_value);
}
constexpr int64_t ms_or(int64_t fallback_value) const {
return IsFinite() ? UnsafeMillis() : fallback_value;
return ToFractionOr<1000>(fallback_value);
}
constexpr int64_t us_or(int64_t fallback_value) const {
return IsFinite() ? microseconds_ : fallback_value;
return ToValueOr(fallback_value);
}
constexpr bool IsFinite() const { return !IsInfinite(); }
constexpr bool IsInfinite() const {
return microseconds_ == timedelta_impl::kPlusInfinityVal ||
microseconds_ == timedelta_impl::kMinusInfinityVal;
}
constexpr bool IsPlusInfinity() const {
return microseconds_ == timedelta_impl::kPlusInfinityVal;
}
constexpr bool IsMinusInfinity() const {
return microseconds_ == timedelta_impl::kMinusInfinityVal;
}
Timestamp operator+(const TimeDelta& other) const {
if (IsPlusInfinity() || other.IsPlusInfinity()) {
Timestamp operator+(const TimeDelta delta) const {
if (IsPlusInfinity() || delta.IsPlusInfinity()) {
RTC_DCHECK(!IsMinusInfinity());
RTC_DCHECK(!other.IsMinusInfinity());
RTC_DCHECK(!delta.IsMinusInfinity());
return PlusInfinity();
} else if (IsMinusInfinity() || other.IsMinusInfinity()) {
} else if (IsMinusInfinity() || delta.IsMinusInfinity()) {
RTC_DCHECK(!IsPlusInfinity());
RTC_DCHECK(!other.IsPlusInfinity());
RTC_DCHECK(!delta.IsPlusInfinity());
return MinusInfinity();
}
return Timestamp::us(us() + other.us());
return Timestamp::us(us() + delta.us());
}
Timestamp operator-(const TimeDelta& other) const {
if (IsPlusInfinity() || other.IsMinusInfinity()) {
Timestamp operator-(const TimeDelta delta) const {
if (IsPlusInfinity() || delta.IsMinusInfinity()) {
RTC_DCHECK(!IsMinusInfinity());
RTC_DCHECK(!other.IsPlusInfinity());
RTC_DCHECK(!delta.IsPlusInfinity());
return PlusInfinity();
} else if (IsMinusInfinity() || other.IsPlusInfinity()) {
} else if (IsMinusInfinity() || delta.IsPlusInfinity()) {
RTC_DCHECK(!IsPlusInfinity());
RTC_DCHECK(!other.IsMinusInfinity());
RTC_DCHECK(!delta.IsMinusInfinity());
return MinusInfinity();
}
return Timestamp::us(us() - other.us());
return Timestamp::us(us() - delta.us());
}
TimeDelta operator-(const Timestamp& other) const {
TimeDelta operator-(const Timestamp other) const {
if (IsPlusInfinity() || other.IsMinusInfinity()) {
RTC_DCHECK(!IsMinusInfinity());
RTC_DCHECK(!other.IsPlusInfinity());
@ -211,45 +114,22 @@ class Timestamp {
}
return TimeDelta::us(us() - other.us());
}
Timestamp& operator-=(const TimeDelta& other) {
*this = *this - other;
Timestamp& operator-=(const TimeDelta delta) {
*this = *this - delta;
return *this;
}
Timestamp& operator+=(const TimeDelta& other) {
*this = *this + other;
Timestamp& operator+=(const TimeDelta delta) {
*this = *this + delta;
return *this;
}
constexpr bool operator==(const Timestamp& other) const {
return microseconds_ == other.microseconds_;
}
constexpr bool operator!=(const Timestamp& other) const {
return microseconds_ != other.microseconds_;
}
constexpr bool operator<=(const Timestamp& other) const {
return microseconds_ <= other.microseconds_;
}
constexpr bool operator>=(const Timestamp& other) const {
return microseconds_ >= other.microseconds_;
}
constexpr bool operator>(const Timestamp& other) const {
return microseconds_ > other.microseconds_;
}
constexpr bool operator<(const Timestamp& other) const {
return microseconds_ < other.microseconds_;
}
private:
explicit constexpr Timestamp(int64_t us) : microseconds_(us) {}
constexpr int64_t UnsafeSeconds() const {
return (microseconds_ + 500000) / 1000000;
}
constexpr int64_t UnsafeMillis() const {
return (microseconds_ + 500) / 1000;
}
int64_t microseconds_;
friend class rtc_units_impl::UnitBase<Timestamp>;
using UnitBase::UnitBase;
static constexpr bool one_sided = true;
};
std::string ToString(const Timestamp& value);
std::string ToString(Timestamp value);
#ifdef UNIT_TEST
inline std::ostream& operator<<( // no-presubmit-check TODO(webrtc:8982)

37
rtc_base/units/BUILD.gn Normal file
View File

@ -0,0 +1,37 @@
# Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
import("../../webrtc.gni")
rtc_source_set("unit_base") {
visibility = [
"../../api/units:*",
":*",
]
sources = [
"unit_base.h",
]
deps = [
"../../rtc_base:checks",
"../../rtc_base:safe_conversions",
]
}
if (rtc_include_tests) {
rtc_source_set("units_unittests") {
testonly = true
sources = [
"unit_base_unittest.cc",
]
deps = [
":unit_base",
"../../test:test_support",
]
}
}

304
rtc_base/units/unit_base.h Normal file
View File

@ -0,0 +1,304 @@
/*
* Copyright 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_UNITS_UNIT_BASE_H_
#define RTC_BASE_UNITS_UNIT_BASE_H_
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <type_traits>
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_conversions.h"
namespace webrtc {
namespace rtc_units_impl {
// UnitBase is a base class for implementing custom value types with a specific
// unit. It provides type safety and sommonly useful operations. The undelying
// storage is always an int64_t, it's up to the unit implementation to choose
// what scale it represents.
//
// It's used like:
// class MyUnit: public UnitBase<MyUnit> {...};
//
// Unit_T is the subclass representing the specific unit.
template <class Unit_T>
class UnitBase {
public:
UnitBase() = delete;
static constexpr Unit_T Zero() { return Unit_T(0); }
static constexpr Unit_T PlusInfinity() { return Unit_T(PlusInfinityVal()); }
static constexpr Unit_T MinusInfinity() { return Unit_T(MinusInfinityVal()); }
constexpr bool IsZero() const { return value_ == 0; }
constexpr bool IsFinite() const { return !IsInfinite(); }
constexpr bool IsInfinite() const {
return value_ == PlusInfinityVal() || value_ == MinusInfinityVal();
}
constexpr bool IsPlusInfinity() const { return value_ == PlusInfinityVal(); }
constexpr bool IsMinusInfinity() const {
return value_ == MinusInfinityVal();
}
constexpr bool operator==(const Unit_T& other) const {
return value_ == other.value_;
}
constexpr bool operator!=(const Unit_T& other) const {
return value_ != other.value_;
}
constexpr bool operator<=(const Unit_T& other) const {
return value_ <= other.value_;
}
constexpr bool operator>=(const Unit_T& other) const {
return value_ >= other.value_;
}
constexpr bool operator>(const Unit_T& other) const {
return value_ > other.value_;
}
constexpr bool operator<(const Unit_T& other) const {
return value_ < other.value_;
}
protected:
template <int64_t value>
static constexpr Unit_T FromStaticValue() {
static_assert(value >= 0 || !Unit_T::one_sided, "");
static_assert(value > MinusInfinityVal(), "");
static_assert(value < PlusInfinityVal(), "");
return Unit_T(value);
}
template <int64_t fraction_value, int64_t Denominator>
static constexpr Unit_T FromStaticFraction() {
static_assert(fraction_value >= 0 || !Unit_T::one_sided, "");
static_assert(fraction_value > MinusInfinityVal() / Denominator, "");
static_assert(fraction_value < PlusInfinityVal() / Denominator, "");
return Unit_T(fraction_value * Denominator);
}
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
static Unit_T FromValue(T value) {
if (Unit_T::one_sided)
RTC_DCHECK_GE(value, 0);
RTC_DCHECK_GT(value, MinusInfinityVal());
RTC_DCHECK_LT(value, PlusInfinityVal());
return Unit_T(rtc::dchecked_cast<int64_t>(value));
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static Unit_T FromValue(T value) {
if (value == std::numeric_limits<T>::infinity()) {
return PlusInfinity();
} else if (value == -std::numeric_limits<T>::infinity()) {
return MinusInfinity();
} else {
RTC_DCHECK(!std::isnan(value));
return FromValue(rtc::dchecked_cast<int64_t>(value));
}
}
template <
int64_t Denominator,
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
static Unit_T FromFraction(T value) {
if (Unit_T::one_sided)
RTC_DCHECK_GE(value, 0);
RTC_DCHECK_GT(value, MinusInfinityVal() / Denominator);
RTC_DCHECK_LT(value, PlusInfinityVal() / Denominator);
return Unit_T(rtc::dchecked_cast<int64_t>(value * Denominator));
}
template <int64_t Denominator,
typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static Unit_T FromFraction(T value) {
return FromValue(value * Denominator);
}
template <typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type ToValue() const {
RTC_DCHECK(IsFinite());
return rtc::dchecked_cast<T>(value_);
}
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
ToValue() const {
return IsPlusInfinity()
? std::numeric_limits<T>::infinity()
: IsMinusInfinity() ? -std::numeric_limits<T>::infinity()
: value_;
}
template <typename T>
constexpr T ToValueOr(T fallback_value) const {
return IsFinite() ? value_ : fallback_value;
}
template <int64_t Denominator, typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type ToFraction()
const {
RTC_DCHECK(IsFinite());
if (Unit_T::one_sided) {
return rtc::dchecked_cast<T>(
DivRoundPositiveToNearest(value_, Denominator));
} else {
return rtc::dchecked_cast<T>(DivRoundToNearest(value_, Denominator));
}
}
template <int64_t Denominator, typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
ToFraction() const {
return ToValue<T>() * (1 / static_cast<T>(Denominator));
}
template <int64_t Denominator>
constexpr int64_t ToFractionOr(int64_t fallback_value) const {
return IsFinite() ? Unit_T::one_sided
? DivRoundPositiveToNearest(value_, Denominator)
: DivRoundToNearest(value_, Denominator)
: fallback_value;
}
template <int64_t Factor, typename T = int64_t>
typename std::enable_if<std::is_integral<T>::value, T>::type ToMultiple()
const {
RTC_DCHECK_GE(ToValue(), std::numeric_limits<T>::min() / Factor);
RTC_DCHECK_LE(ToValue(), std::numeric_limits<T>::max() / Factor);
return rtc::dchecked_cast<T>(ToValue() * Factor);
}
template <int64_t Factor, typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
ToMultiple() const {
return ToValue<T>() * Factor;
}
explicit constexpr UnitBase(int64_t value) : value_(value) {}
private:
template <class RelativeUnit_T>
friend class RelativeUnit;
static inline constexpr int64_t PlusInfinityVal() {
return std::numeric_limits<int64_t>::max();
}
static inline constexpr int64_t MinusInfinityVal() {
return std::numeric_limits<int64_t>::min();
}
Unit_T& AsSubClassRef() { return reinterpret_cast<Unit_T&>(*this); }
constexpr const Unit_T& AsSubClassRef() const {
return reinterpret_cast<const Unit_T&>(*this);
}
// Assumes that n >= 0 and d > 0.
static constexpr int64_t DivRoundPositiveToNearest(int64_t n, int64_t d) {
return (n + d / 2) / d;
}
// Assumes that d > 0.
static constexpr int64_t DivRoundToNearest(int64_t n, int64_t d) {
return (n + (n >= 0 ? d / 2 : -d / 2)) / d;
}
int64_t value_;
};
// Extends UnitBase to provide operations for relative units, that is, units
// that have a meaningful relation between values such that a += b is a
// sensible thing to do. For a,b <- same unit.
template <class Unit_T>
class RelativeUnit : public UnitBase<Unit_T> {
public:
Unit_T Clamped(Unit_T min_value, Unit_T max_value) const {
return std::max(min_value,
std::min(UnitBase<Unit_T>::AsSubClassRef(), max_value));
}
void Clamp(Unit_T min_value, Unit_T max_value) {
*this = Clamped(min_value, max_value);
}
Unit_T operator+(const Unit_T other) const {
if (this->IsPlusInfinity() || other.IsPlusInfinity()) {
RTC_DCHECK(!this->IsMinusInfinity());
RTC_DCHECK(!other.IsMinusInfinity());
return this->PlusInfinity();
} else if (this->IsMinusInfinity() || other.IsMinusInfinity()) {
RTC_DCHECK(!this->IsPlusInfinity());
RTC_DCHECK(!other.IsPlusInfinity());
return this->MinusInfinity();
}
return UnitBase<Unit_T>::FromValue(this->ToValue() + other.ToValue());
}
Unit_T operator-(const Unit_T other) const {
if (this->IsPlusInfinity() || other.IsMinusInfinity()) {
RTC_DCHECK(!this->IsMinusInfinity());
RTC_DCHECK(!other.IsPlusInfinity());
return this->PlusInfinity();
} else if (this->IsMinusInfinity() || other.IsPlusInfinity()) {
RTC_DCHECK(!this->IsPlusInfinity());
RTC_DCHECK(!other.IsMinusInfinity());
return this->MinusInfinity();
}
return UnitBase<Unit_T>::FromValue(this->ToValue() - other.ToValue());
}
Unit_T& operator+=(const Unit_T other) {
*this = *this + other;
return this->AsSubClassRef();
}
Unit_T& operator-=(const Unit_T other) {
*this = *this - other;
return this->AsSubClassRef();
}
constexpr double operator/(const Unit_T other) const {
return UnitBase<Unit_T>::template ToValue<double>() /
other.template ToValue<double>();
}
template <typename T>
typename std::enable_if<std::is_arithmetic<T>::value, Unit_T>::type operator/(
const T& scalar) const {
return UnitBase<Unit_T>::FromValue(
std::round(UnitBase<Unit_T>::template ToValue<int64_t>() / scalar));
}
Unit_T operator*(const double scalar) const {
return UnitBase<Unit_T>::FromValue(std::round(this->ToValue() * scalar));
}
Unit_T operator*(const int64_t scalar) const {
return UnitBase<Unit_T>::FromValue(this->ToValue() * scalar);
}
Unit_T operator*(const int32_t scalar) const {
return UnitBase<Unit_T>::FromValue(this->ToValue() * scalar);
}
protected:
using UnitBase<Unit_T>::UnitBase;
};
template <class Unit_T>
inline Unit_T operator*(const double scalar, const RelativeUnit<Unit_T> other) {
return other * scalar;
}
template <class Unit_T>
inline Unit_T operator*(const int64_t scalar,
const RelativeUnit<Unit_T> other) {
return other * scalar;
}
template <class Unit_T>
inline Unit_T operator*(const int32_t& scalar,
const RelativeUnit<Unit_T> other) {
return other * scalar;
}
} // namespace rtc_units_impl
} // namespace webrtc
#endif // RTC_BASE_UNITS_UNIT_BASE_H_

View File

@ -0,0 +1,234 @@
/*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/units/unit_base.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
class TestUnit final : public rtc_units_impl::RelativeUnit<TestUnit> {
public:
TestUnit() = delete;
using UnitBase::FromStaticValue;
using UnitBase::FromValue;
using UnitBase::ToValue;
using UnitBase::ToValueOr;
template <int64_t kilo>
static constexpr TestUnit FromStaticKilo() {
return FromStaticFraction<kilo, 1000>();
}
template <typename T>
static TestUnit FromKilo(T kilo) {
return FromFraction<1000>(kilo);
}
template <typename T = int64_t>
T ToKilo() const {
return UnitBase::ToFraction<1000, T>();
}
constexpr int64_t ToKiloOr(int64_t fallback) const {
return UnitBase::ToFractionOr<1000>(fallback);
}
template <typename T>
constexpr T ToMilli() const {
return UnitBase::ToMultiple<1000, T>();
}
private:
friend class UnitBase<TestUnit>;
static constexpr bool one_sided = false;
using RelativeUnit<TestUnit>::RelativeUnit;
};
} // namespace
namespace test {
TEST(UnitBaseTest, ConstExpr) {
constexpr int64_t kValue = -12345;
constexpr TestUnit kTestUnitZero = TestUnit::Zero();
constexpr TestUnit kTestUnitPlusInf = TestUnit::PlusInfinity();
constexpr TestUnit kTestUnitMinusInf = TestUnit::MinusInfinity();
static_assert(kTestUnitZero.IsZero(), "");
static_assert(kTestUnitPlusInf.IsPlusInfinity(), "");
static_assert(kTestUnitMinusInf.IsMinusInfinity(), "");
static_assert(kTestUnitPlusInf.ToKiloOr(-1) == -1, "");
static_assert(kTestUnitPlusInf > kTestUnitZero, "");
constexpr TestUnit kTestUnitKilo = TestUnit::FromStaticKilo<kValue>();
constexpr TestUnit kTestUnitValue = TestUnit::FromStaticValue<kValue>();
static_assert(kTestUnitKilo.ToKiloOr(0) == kValue, "");
static_assert(kTestUnitValue.ToValueOr(0) == kValue, "");
}
TEST(UnitBaseTest, GetBackSameValues) {
const int64_t kValue = 499;
for (int sign = -1; sign <= 1; ++sign) {
int64_t value = kValue * sign;
EXPECT_EQ(TestUnit::FromKilo(value).ToKilo(), value);
EXPECT_EQ(TestUnit::FromValue(value).ToValue<int64_t>(), value);
}
EXPECT_EQ(TestUnit::Zero().ToValue<int64_t>(), 0);
}
TEST(UnitBaseTest, GetDifferentPrefix) {
const int64_t kValue = 3000000;
EXPECT_EQ(TestUnit::FromValue(kValue).ToKilo(), kValue / 1000);
EXPECT_EQ(TestUnit::FromKilo(kValue).ToValue<int64_t>(), kValue * 1000);
}
TEST(UnitBaseTest, IdentityChecks) {
const int64_t kValue = 3000;
EXPECT_TRUE(TestUnit::Zero().IsZero());
EXPECT_FALSE(TestUnit::FromKilo(kValue).IsZero());
EXPECT_TRUE(TestUnit::PlusInfinity().IsInfinite());
EXPECT_TRUE(TestUnit::MinusInfinity().IsInfinite());
EXPECT_FALSE(TestUnit::Zero().IsInfinite());
EXPECT_FALSE(TestUnit::FromKilo(-kValue).IsInfinite());
EXPECT_FALSE(TestUnit::FromKilo(kValue).IsInfinite());
EXPECT_FALSE(TestUnit::PlusInfinity().IsFinite());
EXPECT_FALSE(TestUnit::MinusInfinity().IsFinite());
EXPECT_TRUE(TestUnit::FromKilo(-kValue).IsFinite());
EXPECT_TRUE(TestUnit::FromKilo(kValue).IsFinite());
EXPECT_TRUE(TestUnit::Zero().IsFinite());
EXPECT_TRUE(TestUnit::PlusInfinity().IsPlusInfinity());
EXPECT_FALSE(TestUnit::MinusInfinity().IsPlusInfinity());
EXPECT_TRUE(TestUnit::MinusInfinity().IsMinusInfinity());
EXPECT_FALSE(TestUnit::PlusInfinity().IsMinusInfinity());
}
TEST(UnitBaseTest, ComparisonOperators) {
const int64_t kSmall = 450;
const int64_t kLarge = 451;
const TestUnit small = TestUnit::FromKilo(kSmall);
const TestUnit large = TestUnit::FromKilo(kLarge);
EXPECT_EQ(TestUnit::Zero(), TestUnit::FromKilo(0));
EXPECT_EQ(TestUnit::PlusInfinity(), TestUnit::PlusInfinity());
EXPECT_EQ(small, TestUnit::FromKilo(kSmall));
EXPECT_LE(small, TestUnit::FromKilo(kSmall));
EXPECT_GE(small, TestUnit::FromKilo(kSmall));
EXPECT_NE(small, TestUnit::FromKilo(kLarge));
EXPECT_LE(small, TestUnit::FromKilo(kLarge));
EXPECT_LT(small, TestUnit::FromKilo(kLarge));
EXPECT_GE(large, TestUnit::FromKilo(kSmall));
EXPECT_GT(large, TestUnit::FromKilo(kSmall));
EXPECT_LT(TestUnit::Zero(), small);
EXPECT_GT(TestUnit::Zero(), TestUnit::FromKilo(-kSmall));
EXPECT_GT(TestUnit::Zero(), TestUnit::FromKilo(-kSmall));
EXPECT_GT(TestUnit::PlusInfinity(), large);
EXPECT_LT(TestUnit::MinusInfinity(), TestUnit::Zero());
}
TEST(UnitBaseTest, Clamping) {
const TestUnit upper = TestUnit::FromKilo(800);
const TestUnit lower = TestUnit::FromKilo(100);
const TestUnit under = TestUnit::FromKilo(100);
const TestUnit inside = TestUnit::FromKilo(500);
const TestUnit over = TestUnit::FromKilo(1000);
EXPECT_EQ(under.Clamped(lower, upper), lower);
EXPECT_EQ(inside.Clamped(lower, upper), inside);
EXPECT_EQ(over.Clamped(lower, upper), upper);
TestUnit mutable_delta = lower;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, lower);
mutable_delta = inside;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, inside);
mutable_delta = over;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, upper);
}
TEST(UnitBaseTest, CanBeInititializedFromLargeInt) {
const int kMaxInt = std::numeric_limits<int>::max();
EXPECT_EQ(TestUnit::FromKilo(kMaxInt).ToValue<int64_t>(),
static_cast<int64_t>(kMaxInt) * 1000);
}
TEST(UnitBaseTest, ConvertsToAndFromDouble) {
const int64_t kValue = 17017;
const double kMilliDouble = kValue * 1e3;
const double kValueDouble = kValue;
const double kKiloDouble = kValue * 1e-3;
EXPECT_EQ(TestUnit::FromValue(kValue).ToKilo<double>(), kKiloDouble);
EXPECT_EQ(TestUnit::FromKilo(kKiloDouble).ToValue<int64_t>(), kValue);
EXPECT_EQ(TestUnit::FromValue(kValue).ToValue<double>(), kValueDouble);
EXPECT_EQ(TestUnit::FromValue(kValueDouble).ToValue<int64_t>(), kValue);
EXPECT_NEAR(TestUnit::FromValue(kValue).ToMilli<double>(), kMilliDouble, 1);
const double kPlusInfinity = std::numeric_limits<double>::infinity();
const double kMinusInfinity = -kPlusInfinity;
EXPECT_EQ(TestUnit::PlusInfinity().ToKilo<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToKilo<double>(), kMinusInfinity);
EXPECT_EQ(TestUnit::PlusInfinity().ToValue<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToValue<double>(), kMinusInfinity);
EXPECT_EQ(TestUnit::PlusInfinity().ToMilli<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToMilli<double>(), kMinusInfinity);
EXPECT_TRUE(TestUnit::FromKilo(kPlusInfinity).IsPlusInfinity());
EXPECT_TRUE(TestUnit::FromKilo(kMinusInfinity).IsMinusInfinity());
EXPECT_TRUE(TestUnit::FromValue(kPlusInfinity).IsPlusInfinity());
EXPECT_TRUE(TestUnit::FromValue(kMinusInfinity).IsMinusInfinity());
}
TEST(UnitBaseTest, MathOperations) {
const int64_t kValueA = 267;
const int64_t kValueB = 450;
const TestUnit delta_a = TestUnit::FromKilo(kValueA);
const TestUnit delta_b = TestUnit::FromKilo(kValueB);
EXPECT_EQ((delta_a + delta_b).ToKilo(), kValueA + kValueB);
EXPECT_EQ((delta_a - delta_b).ToKilo(), kValueA - kValueB);
const int32_t kInt32Value = 123;
const double kFloatValue = 123.0;
EXPECT_EQ((TestUnit::FromValue(kValueA) * kValueB).ToValue<int64_t>(),
kValueA * kValueB);
EXPECT_EQ((TestUnit::FromValue(kValueA) * kInt32Value).ToValue<int64_t>(),
kValueA * kInt32Value);
EXPECT_EQ((TestUnit::FromValue(kValueA) * kFloatValue).ToValue<int64_t>(),
kValueA * kFloatValue);
EXPECT_EQ((delta_b / 10).ToKilo(), kValueB / 10);
EXPECT_EQ(delta_b / delta_a, static_cast<double>(kValueB) / kValueA);
TestUnit mutable_delta = TestUnit::FromKilo(kValueA);
mutable_delta += TestUnit::FromKilo(kValueB);
EXPECT_EQ(mutable_delta, TestUnit::FromKilo(kValueA + kValueB));
mutable_delta -= TestUnit::FromKilo(kValueB);
EXPECT_EQ(mutable_delta, TestUnit::FromKilo(kValueA));
}
TEST(UnitBaseTest, InfinityOperations) {
const int64_t kValue = 267;
const TestUnit finite = TestUnit::FromKilo(kValue);
EXPECT_TRUE((TestUnit::PlusInfinity() + finite).IsPlusInfinity());
EXPECT_TRUE((TestUnit::PlusInfinity() - finite).IsPlusInfinity());
EXPECT_TRUE((finite + TestUnit::PlusInfinity()).IsPlusInfinity());
EXPECT_TRUE((finite - TestUnit::MinusInfinity()).IsPlusInfinity());
EXPECT_TRUE((TestUnit::MinusInfinity() + finite).IsMinusInfinity());
EXPECT_TRUE((TestUnit::MinusInfinity() - finite).IsMinusInfinity());
EXPECT_TRUE((finite + TestUnit::MinusInfinity()).IsMinusInfinity());
EXPECT_TRUE((finite - TestUnit::PlusInfinity()).IsMinusInfinity());
}
} // namespace test
} // namespace webrtc