| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
| 2 |
/* vim: set ts=8 sts=2 et sw=2 tw=80: */ |
| 3 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
#ifndef ProportionValue_h |
| 8 |
#define ProportionValue_h |
| 9 |
|
| 10 |
#include "mozilla/Attributes.h" |
| 11 |
|
| 12 |
#include <algorithm> |
| 13 |
#include <limits> |
| 14 |
|
| 15 |
namespace mozilla { |
| 16 |
|
| 17 |
// Class storing a proportion value between 0 and 1, effectively 0% to 100%. |
| 18 |
// The public interface deals with doubles, but internally the value is encoded |
| 19 |
// in an integral type, so arithmetic operations are fast. |
| 20 |
// It also supports an invalid value: Use MakeInvalid() to construct, it infects |
| 21 |
// any operation, and gets converted to a signaling NaN. |
| 22 |
class ProportionValue { |
| 23 |
public: |
| 24 |
using UnderlyingType = uint32_t; |
| 25 |
|
| 26 |
// Default-construct at 0%. |
| 27 |
constexpr ProportionValue() |
| 28 |
// This `noexcept` is necessary to avoid a build error when encapsulating |
| 29 |
// `ProportionValue` in `std::Atomic`: |
| 30 |
// "use of deleted function |
| 31 |
// 'constexpr std::atomic<mozilla::ProportionValue>::atomic()" |
| 32 |
// because the default `std::atomic<T>::atomic()` constructor is marked: |
| 33 |
// `noexcept(std::is_nothrow_default_constructible_v<T>)` |
| 34 |
// and therefore this default constructor here must be explicitly marked |
| 35 |
// `noexcept` as well. |
| 36 |
noexcept |
| 37 |
: mIntegralValue(0u) {} |
| 38 |
|
| 39 |
// Construct a ProportionValue with the given value, clamped to 0..1. |
| 40 |
// Note that it's constexpr, so construction from literal numbers should incur |
| 41 |
// no runtime costs. |
| 42 |
// If `aValue` is NaN, behavior is undefined! Use `MakeInvalid()` instead. |
| 43 |
constexpr explicit ProportionValue(double aValue) |
| 44 |
: mIntegralValue(UnderlyingType(std::clamp(aValue, 0.0, 1.0) * scMaxD)) {} |
| 45 |
|
| 46 |
[[nodiscard]] static constexpr ProportionValue MakeInvalid() { |
| 47 |
return ProportionValue(scInvalidU, Internal{}); |
| 48 |
} |
| 49 |
|
| 50 |
[[nodiscard]] constexpr double ToDouble() const { |
| 51 |
return IsInvalid() ? std::numeric_limits<double>::signaling_NaN() |
| 52 |
: (double(mIntegralValue) * scInvMaxD); |
| 53 |
} |
| 54 |
|
| 55 |
// Retrieve the underlying integral value, for storage or testing purposes. |
| 56 |
[[nodiscard]] constexpr UnderlyingType ToUnderlyingType() const { |
| 57 |
return mIntegralValue; |
| 58 |
}; |
| 59 |
|
| 60 |
// Re-construct a ProportionValue from an underlying integral value. |
| 61 |
[[nodiscard]] static constexpr ProportionValue FromUnderlyingType( |
| 62 |
UnderlyingType aUnderlyingType) { |
| 63 |
return ProportionValue( |
| 64 |
(aUnderlyingType <= scMaxU) ? aUnderlyingType : scInvalidU, Internal{}); |
| 65 |
} |
| 66 |
|
| 67 |
[[nodiscard]] constexpr bool IsExactlyZero() const { |
| 68 |
return mIntegralValue == 0u; |
| 69 |
} |
| 70 |
|
| 71 |
[[nodiscard]] constexpr bool IsExactlyOne() const { |
| 72 |
return mIntegralValue == scMaxU; |
| 73 |
} |
| 74 |
|
| 75 |
[[nodiscard]] constexpr bool IsValid() const { |
| 76 |
// Compare to the maximum value, not just exactly scInvalidU, to catch any |
| 77 |
// kind of invalid state. |
| 78 |
return mIntegralValue <= scMaxU; |
| 79 |
} |
| 80 |
[[nodiscard]] constexpr bool IsInvalid() const { |
| 81 |
// Compare to the maximum value, not just exactly scInvalidU, to catch any |
| 82 |
// kind of invalid state. |
| 83 |
return mIntegralValue > scMaxU; |
| 84 |
} |
| 85 |
|
| 86 |
// Strict comparisons based on the underlying integral value. Use |
| 87 |
// `CompareWithin` instead to make fuzzy comparisons. |
| 88 |
// `ProportionValue::MakeInvalid()`s are equal, and greater than anything |
| 89 |
// else; Best to avoid comparisons, and first use IsInvalid() instead. |
| 90 |
#define OPERATOR_COMPARISON(CMP) \ |
| 91 |
[[nodiscard]] constexpr friend bool operator CMP( \ |
| 92 |
const ProportionValue& aLHS, const ProportionValue& aRHS) { \ |
| 93 |
return aLHS.mIntegralValue CMP aRHS.mIntegralValue; \ |
| 94 |
} |
| 95 |
OPERATOR_COMPARISON(==) |
| 96 |
OPERATOR_COMPARISON(!=) |
| 97 |
OPERATOR_COMPARISON(<) |
| 98 |
OPERATOR_COMPARISON(<=) |
| 99 |
OPERATOR_COMPARISON(>) |
| 100 |
OPERATOR_COMPARISON(>=) |
| 101 |
#undef OPERATOR_COMPARISON |
| 102 |
|
| 103 |
// Arithmetic operations + - *, all working on the underlying integral values |
| 104 |
// (i.e, no expensive floating-point operations are used), and always clamping |
| 105 |
// to 0..1 range. Invalid values are poisonous. |
| 106 |
|
| 107 |
[[nodiscard]] constexpr ProportionValue operator+( |
| 108 |
ProportionValue aRHS) const { |
| 109 |
return ProportionValue( |
| 110 |
(IsInvalid() || aRHS.IsInvalid()) |
| 111 |
? scInvalidU |
| 112 |
// Adding fixed-point values keep the same scale, so there is no |
| 113 |
// adjustment needed for that. [0,1]+[0,1]=[0,2], so we only need to |
| 114 |
// ensure that the result is capped at max 1, aka scMaxU: |
| 115 |
// a+b<=max <=> b<=max-a, so b is at maximum max-a. |
| 116 |
: (mIntegralValue + |
| 117 |
std::min(aRHS.mIntegralValue, scMaxU - mIntegralValue)), |
| 118 |
Internal{}); |
| 119 |
} |
| 120 |
|
| 121 |
[[nodiscard]] constexpr ProportionValue operator-( |
| 122 |
ProportionValue aRHS) const { |
| 123 |
return ProportionValue( |
| 124 |
(IsInvalid() || aRHS.IsInvalid()) |
| 125 |
? scInvalidU |
| 126 |
// Subtracting fixed-point values keep the same scale, so there is |
| 127 |
// no adjustment needed for that. [0,1]-[0,1]=[-1,1], so we only |
| 128 |
// need to ensure that the value is positive: |
| 129 |
// a-b>=0 <=> b<=a, so b is at maximum a. |
| 130 |
: (mIntegralValue - std::min(aRHS.mIntegralValue, mIntegralValue)), |
| 131 |
Internal{}); |
| 132 |
} |
| 133 |
|
| 134 |
[[nodiscard]] constexpr ProportionValue operator*( |
| 135 |
ProportionValue aRHS) const { |
| 136 |
// Type to hold the full result of multiplying two maximum numbers. |
| 137 |
using DoublePrecisionType = uint64_t; |
| 138 |
static_assert(sizeof(DoublePrecisionType) >= 2 * sizeof(UnderlyingType)); |
| 139 |
return ProportionValue( |
| 140 |
(IsInvalid() || aRHS.IsInvalid()) |
| 141 |
? scInvalidU |
| 142 |
// Multiplying fixed-point values doubles the scale (2^31 -> 2^62), |
| 143 |
// so we need to adjust the result by dividing it by one scale |
| 144 |
// (which is optimized into a binary right-shift). |
| 145 |
: (UnderlyingType((DoublePrecisionType(mIntegralValue) * |
| 146 |
DoublePrecisionType(aRHS.mIntegralValue)) / |
| 147 |
DoublePrecisionType(scMaxU))), |
| 148 |
Internal{}); |
| 149 |
} |
| 150 |
|
| 151 |
// Explicitly forbid divisions, they make little sense, and would almost |
| 152 |
// always return a clamped 100% (E.g.: 50% / 10% = 0.5 / 0.1 = 5 = 500%). |
| 153 |
[[nodiscard]] constexpr ProportionValue operator/( |
| 154 |
ProportionValue aRHS) const = delete; |
| 155 |
|
| 156 |
// Division by a positive integer value, useful to split an interval in equal |
| 157 |
// parts (with maybe some spare space at the end, because it is rounded down). |
| 158 |
// Division by 0 produces an invalid value. |
| 159 |
[[nodiscard]] constexpr ProportionValue operator/(uint32_t aDivisor) const { |
| 160 |
return ProportionValue((IsInvalid() || aDivisor == 0u) |
| 161 |
? scInvalidU |
| 162 |
: (mIntegralValue / aDivisor), |
| 163 |
Internal{}); |
| 164 |
} |
| 165 |
|
| 166 |
// Multiplication by a positive integer value, useful as inverse of the |
| 167 |
// integer division above. But it may be lossy because the division is rounded |
| 168 |
// down, therefore: PV - u < (PV / u) * u <= PV. |
| 169 |
// Clamped to 100% max. |
| 170 |
[[nodiscard]] constexpr ProportionValue operator*( |
| 171 |
uint32_t aMultiplier) const { |
| 172 |
return ProportionValue(IsInvalid() |
| 173 |
? scInvalidU |
| 174 |
: ((aMultiplier > scMaxU / mIntegralValue) |
| 175 |
? scMaxU |
| 176 |
: (mIntegralValue * aMultiplier)), |
| 177 |
Internal{}); |
| 178 |
} |
| 179 |
|
| 180 |
private: |
| 181 |
// Tagged constructor for internal construction from the UnderlyingType, so |
| 182 |
// that it is never ambiguously considered in constructions from one number. |
| 183 |
struct Internal {}; |
| 184 |
constexpr ProportionValue(UnderlyingType aIntegralValue, Internal) |
| 185 |
: mIntegralValue(aIntegralValue) {} |
| 186 |
|
| 187 |
// Use all but 1 bit for the fractional part. |
| 188 |
// Valid values can go from 0b0 (0%) up to 0b1000...00 (scMaxU aka 100%). |
| 189 |
static constexpr unsigned scFractionalBits = sizeof(UnderlyingType) * 8 - 1; |
| 190 |
// Maximum value corresponding to 1.0 or 100%. |
| 191 |
static constexpr UnderlyingType scMaxU = UnderlyingType(1u) |
| 192 |
<< scFractionalBits; |
| 193 |
// This maximum value corresponding to 1.0 can also be seen as the scaling |
| 194 |
// factor from any [0,1] `double` value to the internal integral value. |
| 195 |
static constexpr double scMaxD = double(scMaxU); |
| 196 |
// The inverse can be used to convert the internal value back to [0,1]. |
| 197 |
static constexpr double scInvMaxD = 1.0 / scMaxD; |
| 198 |
|
| 199 |
// Special value outside [0,max], used to construct invalid values. |
| 200 |
static constexpr UnderlyingType scInvalidU = ~UnderlyingType(0u); |
| 201 |
|
| 202 |
// Internal integral value, guaranteed to always be <= scMaxU, or scInvalidU. |
| 203 |
// This is effectively a fixed-point value using 1 bit for the integer part |
| 204 |
// and 31 bits for the fractional part. |
| 205 |
// It is roughly equal to the `double` value [0,1] multiplied by scMaxD. |
| 206 |
UnderlyingType mIntegralValue; |
| 207 |
}; |
| 208 |
|
| 209 |
namespace literals { |
| 210 |
inline namespace ProportionValue_literals { |
| 211 |
|
| 212 |
// User-defined literal for integer percentages, e.g.: `10_pc`, `100_pc` |
| 213 |
// (equivalent to `ProportionValue{0.1}` and `ProportionValue{1.0}`). |
| 214 |
// Clamped to [0, 100]_pc. |
| 215 |
[[nodiscard]] constexpr ProportionValue operator""_pc( |
| 216 |
unsigned long long int aPercentage) { |
| 217 |
return ProportionValue{ |
| 218 |
double(std::clamp<unsigned long long int>(aPercentage, 0u, 100u)) / |
| 219 |
100.0}; |
| 220 |
} |
| 221 |
|
| 222 |
// User-defined literal for non-integer percentages, e.g.: `12.3_pc`, `100.0_pc` |
| 223 |
// (equivalent to `ProportionValue{0.123}` and `ProportionValue{1.0}`). |
| 224 |
// Clamped to [0.0, 100.0]_pc. |
| 225 |
[[nodiscard]] constexpr ProportionValue operator""_pc(long double aPercentage) { |
| 226 |
return ProportionValue{ |
| 227 |
double(std::clamp<long double>(aPercentage, 0.0, 100.0)) / 100.0}; |
| 228 |
} |
| 229 |
|
| 230 |
} // namespace ProportionValue_literals |
| 231 |
} // namespace literals |
| 232 |
|
| 233 |
} // namespace mozilla |
| 234 |
|
| 235 |
#endif // ProportionValue_h |