annotate win32-mingw/include/kj/units.h @ 163:5cc1366da2e9

Apply patch from Tim Bunnell on PortAudio mailing list (2016-12-28, Mac 10.11 deprecation warning)
author Chris Cannam <cannam@all-day-breakfast.com>
date Wed, 30 Oct 2019 11:28:45 +0000
parents 279b18cc7785
children
rev   line source
cannam@149 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
cannam@149 2 // Licensed under the MIT License:
cannam@149 3 //
cannam@149 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
cannam@149 5 // of this software and associated documentation files (the "Software"), to deal
cannam@149 6 // in the Software without restriction, including without limitation the rights
cannam@149 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
cannam@149 8 // copies of the Software, and to permit persons to whom the Software is
cannam@149 9 // furnished to do so, subject to the following conditions:
cannam@149 10 //
cannam@149 11 // The above copyright notice and this permission notice shall be included in
cannam@149 12 // all copies or substantial portions of the Software.
cannam@149 13 //
cannam@149 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
cannam@149 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
cannam@149 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
cannam@149 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
cannam@149 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
cannam@149 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
cannam@149 20 // THE SOFTWARE.
cannam@149 21
cannam@149 22 // This file contains types which are intended to help detect incorrect usage at compile
cannam@149 23 // time, but should then be optimized down to basic primitives (usually, integers) by the
cannam@149 24 // compiler.
cannam@149 25
cannam@149 26 #ifndef KJ_UNITS_H_
cannam@149 27 #define KJ_UNITS_H_
cannam@149 28
cannam@149 29 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
cannam@149 30 #pragma GCC system_header
cannam@149 31 #endif
cannam@149 32
cannam@149 33 #include "common.h"
cannam@149 34 #include <inttypes.h>
cannam@149 35
cannam@149 36 namespace kj {
cannam@149 37
cannam@149 38 // =======================================================================================
cannam@149 39 // IDs
cannam@149 40
cannam@149 41 template <typename UnderlyingType, typename Label>
cannam@149 42 struct Id {
cannam@149 43 // A type-safe numeric ID. `UnderlyingType` is the underlying integer representation. `Label`
cannam@149 44 // distinguishes this Id from other Id types. Sample usage:
cannam@149 45 //
cannam@149 46 // class Foo;
cannam@149 47 // typedef Id<uint, Foo> FooId;
cannam@149 48 //
cannam@149 49 // class Bar;
cannam@149 50 // typedef Id<uint, Bar> BarId;
cannam@149 51 //
cannam@149 52 // You can now use the FooId and BarId types without any possibility of accidentally using a
cannam@149 53 // FooId when you really wanted a BarId or vice-versa.
cannam@149 54
cannam@149 55 UnderlyingType value;
cannam@149 56
cannam@149 57 inline constexpr Id(): value(0) {}
cannam@149 58 inline constexpr explicit Id(int value): value(value) {}
cannam@149 59
cannam@149 60 inline constexpr bool operator==(const Id& other) const { return value == other.value; }
cannam@149 61 inline constexpr bool operator!=(const Id& other) const { return value != other.value; }
cannam@149 62 inline constexpr bool operator<=(const Id& other) const { return value <= other.value; }
cannam@149 63 inline constexpr bool operator>=(const Id& other) const { return value >= other.value; }
cannam@149 64 inline constexpr bool operator< (const Id& other) const { return value < other.value; }
cannam@149 65 inline constexpr bool operator> (const Id& other) const { return value > other.value; }
cannam@149 66 };
cannam@149 67
cannam@149 68 // =======================================================================================
cannam@149 69 // Quantity and UnitRatio -- implement unit analysis via the type system
cannam@149 70
cannam@149 71 struct Unsafe_ {};
cannam@149 72 constexpr Unsafe_ unsafe = Unsafe_();
cannam@149 73 // Use as a parameter to constructors that are unsafe to indicate that you really do mean it.
cannam@149 74
cannam@149 75 template <uint64_t maxN, typename T>
cannam@149 76 class Bounded;
cannam@149 77 template <uint value>
cannam@149 78 class BoundedConst;
cannam@149 79
cannam@149 80 template <typename T> constexpr bool isIntegral() { return false; }
cannam@149 81 template <> constexpr bool isIntegral<char>() { return true; }
cannam@149 82 template <> constexpr bool isIntegral<signed char>() { return true; }
cannam@149 83 template <> constexpr bool isIntegral<short>() { return true; }
cannam@149 84 template <> constexpr bool isIntegral<int>() { return true; }
cannam@149 85 template <> constexpr bool isIntegral<long>() { return true; }
cannam@149 86 template <> constexpr bool isIntegral<long long>() { return true; }
cannam@149 87 template <> constexpr bool isIntegral<unsigned char>() { return true; }
cannam@149 88 template <> constexpr bool isIntegral<unsigned short>() { return true; }
cannam@149 89 template <> constexpr bool isIntegral<unsigned int>() { return true; }
cannam@149 90 template <> constexpr bool isIntegral<unsigned long>() { return true; }
cannam@149 91 template <> constexpr bool isIntegral<unsigned long long>() { return true; }
cannam@149 92
cannam@149 93 template <typename T>
cannam@149 94 struct IsIntegralOrBounded_ { static constexpr bool value = isIntegral<T>(); };
cannam@149 95 template <uint64_t m, typename T>
cannam@149 96 struct IsIntegralOrBounded_<Bounded<m, T>> { static constexpr bool value = true; };
cannam@149 97 template <uint v>
cannam@149 98 struct IsIntegralOrBounded_<BoundedConst<v>> { static constexpr bool value = true; };
cannam@149 99
cannam@149 100 template <typename T>
cannam@149 101 inline constexpr bool isIntegralOrBounded() { return IsIntegralOrBounded_<T>::value; }
cannam@149 102
cannam@149 103 template <typename Number, typename Unit1, typename Unit2>
cannam@149 104 class UnitRatio {
cannam@149 105 // A multiplier used to convert Quantities of one unit to Quantities of another unit. See
cannam@149 106 // Quantity, below.
cannam@149 107 //
cannam@149 108 // Construct this type by dividing one Quantity by another of a different unit. Use this type
cannam@149 109 // by multiplying it by a Quantity, or dividing a Quantity by it.
cannam@149 110
cannam@149 111 static_assert(isIntegralOrBounded<Number>(),
cannam@149 112 "Underlying type for UnitRatio must be integer.");
cannam@149 113
cannam@149 114 public:
cannam@149 115 inline UnitRatio() {}
cannam@149 116
cannam@149 117 constexpr UnitRatio(Number unit1PerUnit2, decltype(unsafe)): unit1PerUnit2(unit1PerUnit2) {}
cannam@149 118 // This constructor was intended to be private, but GCC complains about it being private in a
cannam@149 119 // bunch of places that don't appear to even call it, so I made it public. Oh well.
cannam@149 120
cannam@149 121 template <typename OtherNumber>
cannam@149 122 inline constexpr UnitRatio(const UnitRatio<OtherNumber, Unit1, Unit2>& other)
cannam@149 123 : unit1PerUnit2(other.unit1PerUnit2) {}
cannam@149 124
cannam@149 125 template <typename OtherNumber>
cannam@149 126 inline constexpr UnitRatio<decltype(Number()+OtherNumber()), Unit1, Unit2>
cannam@149 127 operator+(UnitRatio<OtherNumber, Unit1, Unit2> other) const {
cannam@149 128 return UnitRatio<decltype(Number()+OtherNumber()), Unit1, Unit2>(
cannam@149 129 unit1PerUnit2 + other.unit1PerUnit2, unsafe);
cannam@149 130 }
cannam@149 131 template <typename OtherNumber>
cannam@149 132 inline constexpr UnitRatio<decltype(Number()-OtherNumber()), Unit1, Unit2>
cannam@149 133 operator-(UnitRatio<OtherNumber, Unit1, Unit2> other) const {
cannam@149 134 return UnitRatio<decltype(Number()-OtherNumber()), Unit1, Unit2>(
cannam@149 135 unit1PerUnit2 - other.unit1PerUnit2, unsafe);
cannam@149 136 }
cannam@149 137
cannam@149 138 template <typename OtherNumber, typename Unit3>
cannam@149 139 inline constexpr UnitRatio<decltype(Number()*OtherNumber()), Unit3, Unit2>
cannam@149 140 operator*(UnitRatio<OtherNumber, Unit3, Unit1> other) const {
cannam@149 141 // U1 / U2 * U3 / U1 = U3 / U2
cannam@149 142 return UnitRatio<decltype(Number()*OtherNumber()), Unit3, Unit2>(
cannam@149 143 unit1PerUnit2 * other.unit1PerUnit2, unsafe);
cannam@149 144 }
cannam@149 145 template <typename OtherNumber, typename Unit3>
cannam@149 146 inline constexpr UnitRatio<decltype(Number()*OtherNumber()), Unit1, Unit3>
cannam@149 147 operator*(UnitRatio<OtherNumber, Unit2, Unit3> other) const {
cannam@149 148 // U1 / U2 * U2 / U3 = U1 / U3
cannam@149 149 return UnitRatio<decltype(Number()*OtherNumber()), Unit1, Unit3>(
cannam@149 150 unit1PerUnit2 * other.unit1PerUnit2, unsafe);
cannam@149 151 }
cannam@149 152
cannam@149 153 template <typename OtherNumber, typename Unit3>
cannam@149 154 inline constexpr UnitRatio<decltype(Number()*OtherNumber()), Unit3, Unit2>
cannam@149 155 operator/(UnitRatio<OtherNumber, Unit1, Unit3> other) const {
cannam@149 156 // (U1 / U2) / (U1 / U3) = U3 / U2
cannam@149 157 return UnitRatio<decltype(Number()*OtherNumber()), Unit3, Unit2>(
cannam@149 158 unit1PerUnit2 / other.unit1PerUnit2, unsafe);
cannam@149 159 }
cannam@149 160 template <typename OtherNumber, typename Unit3>
cannam@149 161 inline constexpr UnitRatio<decltype(Number()*OtherNumber()), Unit1, Unit3>
cannam@149 162 operator/(UnitRatio<OtherNumber, Unit3, Unit2> other) const {
cannam@149 163 // (U1 / U2) / (U3 / U2) = U1 / U3
cannam@149 164 return UnitRatio<decltype(Number()*OtherNumber()), Unit1, Unit3>(
cannam@149 165 unit1PerUnit2 / other.unit1PerUnit2, unsafe);
cannam@149 166 }
cannam@149 167
cannam@149 168 template <typename OtherNumber>
cannam@149 169 inline decltype(Number() / OtherNumber())
cannam@149 170 operator/(UnitRatio<OtherNumber, Unit1, Unit2> other) const {
cannam@149 171 return unit1PerUnit2 / other.unit1PerUnit2;
cannam@149 172 }
cannam@149 173
cannam@149 174 inline bool operator==(UnitRatio other) const { return unit1PerUnit2 == other.unit1PerUnit2; }
cannam@149 175 inline bool operator!=(UnitRatio other) const { return unit1PerUnit2 != other.unit1PerUnit2; }
cannam@149 176
cannam@149 177 private:
cannam@149 178 Number unit1PerUnit2;
cannam@149 179
cannam@149 180 template <typename OtherNumber, typename OtherUnit>
cannam@149 181 friend class Quantity;
cannam@149 182 template <typename OtherNumber, typename OtherUnit1, typename OtherUnit2>
cannam@149 183 friend class UnitRatio;
cannam@149 184
cannam@149 185 template <typename N1, typename N2, typename U1, typename U2, typename>
cannam@149 186 friend inline constexpr UnitRatio<decltype(N1() * N2()), U1, U2>
cannam@149 187 operator*(N1, UnitRatio<N2, U1, U2>);
cannam@149 188 };
cannam@149 189
cannam@149 190 template <typename N1, typename N2, typename U1, typename U2,
cannam@149 191 typename = EnableIf<isIntegralOrBounded<N1>() && isIntegralOrBounded<N2>()>>
cannam@149 192 inline constexpr UnitRatio<decltype(N1() * N2()), U1, U2>
cannam@149 193 operator*(N1 n, UnitRatio<N2, U1, U2> r) {
cannam@149 194 return UnitRatio<decltype(N1() * N2()), U1, U2>(n * r.unit1PerUnit2, unsafe);
cannam@149 195 }
cannam@149 196
cannam@149 197 template <typename Number, typename Unit>
cannam@149 198 class Quantity {
cannam@149 199 // A type-safe numeric quantity, specified in terms of some unit. Two Quantities cannot be used
cannam@149 200 // in arithmetic unless they use the same unit. The `Unit` type parameter is only used to prevent
cannam@149 201 // accidental mixing of units; this type is never instantiated and can very well be incomplete.
cannam@149 202 // `Number` is the underlying primitive numeric type.
cannam@149 203 //
cannam@149 204 // Quantities support most basic arithmetic operators, intelligently handling units, and
cannam@149 205 // automatically casting the underlying type in the same way that the compiler would.
cannam@149 206 //
cannam@149 207 // To convert a primitive number to a Quantity, multiply it by unit<Quantity<N, U>>().
cannam@149 208 // To convert a Quantity to a primitive number, divide it by unit<Quantity<N, U>>().
cannam@149 209 // To convert a Quantity of one unit to another unit, multiply or divide by a UnitRatio.
cannam@149 210 //
cannam@149 211 // The Quantity class is not well-suited to hardcore physics as it does not allow multiplying
cannam@149 212 // one quantity by another. For example, multiplying meters by meters won't get you square
cannam@149 213 // meters; it will get you a compiler error. It would be interesting to see if template
cannam@149 214 // metaprogramming could properly deal with such things but this isn't needed for the present
cannam@149 215 // use case.
cannam@149 216 //
cannam@149 217 // Sample usage:
cannam@149 218 //
cannam@149 219 // class SecondsLabel;
cannam@149 220 // typedef Quantity<double, SecondsLabel> Seconds;
cannam@149 221 // constexpr Seconds SECONDS = unit<Seconds>();
cannam@149 222 //
cannam@149 223 // class MinutesLabel;
cannam@149 224 // typedef Quantity<double, MinutesLabel> Minutes;
cannam@149 225 // constexpr Minutes MINUTES = unit<Minutes>();
cannam@149 226 //
cannam@149 227 // constexpr UnitRatio<double, SecondsLabel, MinutesLabel> SECONDS_PER_MINUTE =
cannam@149 228 // 60 * SECONDS / MINUTES;
cannam@149 229 //
cannam@149 230 // void waitFor(Seconds seconds) {
cannam@149 231 // sleep(seconds / SECONDS);
cannam@149 232 // }
cannam@149 233 // void waitFor(Minutes minutes) {
cannam@149 234 // waitFor(minutes * SECONDS_PER_MINUTE);
cannam@149 235 // }
cannam@149 236 //
cannam@149 237 // void waitThreeMinutes() {
cannam@149 238 // waitFor(3 * MINUTES);
cannam@149 239 // }
cannam@149 240
cannam@149 241 static_assert(isIntegralOrBounded<Number>(),
cannam@149 242 "Underlying type for Quantity must be integer.");
cannam@149 243
cannam@149 244 public:
cannam@149 245 inline constexpr Quantity() = default;
cannam@149 246
cannam@149 247 inline constexpr Quantity(MaxValue_): value(maxValue) {}
cannam@149 248 inline constexpr Quantity(MinValue_): value(minValue) {}
cannam@149 249 // Allow initialization from maxValue and minValue.
cannam@149 250 // TODO(msvc): decltype(maxValue) and decltype(minValue) deduce unknown-type for these function
cannam@149 251 // parameters, causing the compiler to complain of a duplicate constructor definition, so we
cannam@149 252 // specify MaxValue_ and MinValue_ types explicitly.
cannam@149 253
cannam@149 254 inline constexpr Quantity(Number value, decltype(unsafe)): value(value) {}
cannam@149 255 // This constructor was intended to be private, but GCC complains about it being private in a
cannam@149 256 // bunch of places that don't appear to even call it, so I made it public. Oh well.
cannam@149 257
cannam@149 258 template <typename OtherNumber>
cannam@149 259 inline constexpr Quantity(const Quantity<OtherNumber, Unit>& other)
cannam@149 260 : value(other.value) {}
cannam@149 261
cannam@149 262 template <typename OtherNumber>
cannam@149 263 inline Quantity& operator=(const Quantity<OtherNumber, Unit>& other) {
cannam@149 264 value = other.value;
cannam@149 265 return *this;
cannam@149 266 }
cannam@149 267
cannam@149 268 template <typename OtherNumber>
cannam@149 269 inline constexpr Quantity<decltype(Number() + OtherNumber()), Unit>
cannam@149 270 operator+(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 271 return Quantity<decltype(Number() + OtherNumber()), Unit>(value + other.value, unsafe);
cannam@149 272 }
cannam@149 273 template <typename OtherNumber>
cannam@149 274 inline constexpr Quantity<decltype(Number() - OtherNumber()), Unit>
cannam@149 275 operator-(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 276 return Quantity<decltype(Number() - OtherNumber()), Unit>(value - other.value, unsafe);
cannam@149 277 }
cannam@149 278 template <typename OtherNumber, typename = EnableIf<isIntegralOrBounded<OtherNumber>()>>
cannam@149 279 inline constexpr Quantity<decltype(Number() * OtherNumber()), Unit>
cannam@149 280 operator*(OtherNumber other) const {
cannam@149 281 return Quantity<decltype(Number() * other), Unit>(value * other, unsafe);
cannam@149 282 }
cannam@149 283 template <typename OtherNumber, typename = EnableIf<isIntegralOrBounded<OtherNumber>()>>
cannam@149 284 inline constexpr Quantity<decltype(Number() / OtherNumber()), Unit>
cannam@149 285 operator/(OtherNumber other) const {
cannam@149 286 return Quantity<decltype(Number() / other), Unit>(value / other, unsafe);
cannam@149 287 }
cannam@149 288 template <typename OtherNumber>
cannam@149 289 inline constexpr decltype(Number() / OtherNumber())
cannam@149 290 operator/(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 291 return value / other.value;
cannam@149 292 }
cannam@149 293 template <typename OtherNumber>
cannam@149 294 inline constexpr Quantity<decltype(Number() % OtherNumber()), Unit>
cannam@149 295 operator%(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 296 return Quantity<decltype(Number() % OtherNumber()), Unit>(value % other.value, unsafe);
cannam@149 297 }
cannam@149 298
cannam@149 299 template <typename OtherNumber, typename OtherUnit>
cannam@149 300 inline constexpr Quantity<decltype(Number() * OtherNumber()), OtherUnit>
cannam@149 301 operator*(UnitRatio<OtherNumber, OtherUnit, Unit> ratio) const {
cannam@149 302 return Quantity<decltype(Number() * OtherNumber()), OtherUnit>(
cannam@149 303 value * ratio.unit1PerUnit2, unsafe);
cannam@149 304 }
cannam@149 305 template <typename OtherNumber, typename OtherUnit>
cannam@149 306 inline constexpr Quantity<decltype(Number() / OtherNumber()), OtherUnit>
cannam@149 307 operator/(UnitRatio<OtherNumber, Unit, OtherUnit> ratio) const {
cannam@149 308 return Quantity<decltype(Number() / OtherNumber()), OtherUnit>(
cannam@149 309 value / ratio.unit1PerUnit2, unsafe);
cannam@149 310 }
cannam@149 311 template <typename OtherNumber, typename OtherUnit>
cannam@149 312 inline constexpr Quantity<decltype(Number() % OtherNumber()), Unit>
cannam@149 313 operator%(UnitRatio<OtherNumber, Unit, OtherUnit> ratio) const {
cannam@149 314 return Quantity<decltype(Number() % OtherNumber()), Unit>(
cannam@149 315 value % ratio.unit1PerUnit2, unsafe);
cannam@149 316 }
cannam@149 317 template <typename OtherNumber, typename OtherUnit>
cannam@149 318 inline constexpr UnitRatio<decltype(Number() / OtherNumber()), Unit, OtherUnit>
cannam@149 319 operator/(Quantity<OtherNumber, OtherUnit> other) const {
cannam@149 320 return UnitRatio<decltype(Number() / OtherNumber()), Unit, OtherUnit>(
cannam@149 321 value / other.value, unsafe);
cannam@149 322 }
cannam@149 323
cannam@149 324 template <typename OtherNumber>
cannam@149 325 inline constexpr bool operator==(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 326 return value == other.value;
cannam@149 327 }
cannam@149 328 template <typename OtherNumber>
cannam@149 329 inline constexpr bool operator!=(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 330 return value != other.value;
cannam@149 331 }
cannam@149 332 template <typename OtherNumber>
cannam@149 333 inline constexpr bool operator<=(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 334 return value <= other.value;
cannam@149 335 }
cannam@149 336 template <typename OtherNumber>
cannam@149 337 inline constexpr bool operator>=(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 338 return value >= other.value;
cannam@149 339 }
cannam@149 340 template <typename OtherNumber>
cannam@149 341 inline constexpr bool operator<(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 342 return value < other.value;
cannam@149 343 }
cannam@149 344 template <typename OtherNumber>
cannam@149 345 inline constexpr bool operator>(const Quantity<OtherNumber, Unit>& other) const {
cannam@149 346 return value > other.value;
cannam@149 347 }
cannam@149 348
cannam@149 349 template <typename OtherNumber>
cannam@149 350 inline Quantity& operator+=(const Quantity<OtherNumber, Unit>& other) {
cannam@149 351 value += other.value;
cannam@149 352 return *this;
cannam@149 353 }
cannam@149 354 template <typename OtherNumber>
cannam@149 355 inline Quantity& operator-=(const Quantity<OtherNumber, Unit>& other) {
cannam@149 356 value -= other.value;
cannam@149 357 return *this;
cannam@149 358 }
cannam@149 359 template <typename OtherNumber>
cannam@149 360 inline Quantity& operator*=(OtherNumber other) {
cannam@149 361 value *= other;
cannam@149 362 return *this;
cannam@149 363 }
cannam@149 364 template <typename OtherNumber>
cannam@149 365 inline Quantity& operator/=(OtherNumber other) {
cannam@149 366 value /= other.value;
cannam@149 367 return *this;
cannam@149 368 }
cannam@149 369
cannam@149 370 private:
cannam@149 371 Number value;
cannam@149 372
cannam@149 373 template <typename OtherNumber, typename OtherUnit>
cannam@149 374 friend class Quantity;
cannam@149 375
cannam@149 376 template <typename Number1, typename Number2, typename Unit2>
cannam@149 377 friend inline constexpr auto operator*(Number1 a, Quantity<Number2, Unit2> b)
cannam@149 378 -> Quantity<decltype(Number1() * Number2()), Unit2>;
cannam@149 379 };
cannam@149 380
cannam@149 381 template <typename T> struct Unit_ {
cannam@149 382 static inline constexpr T get() { return T(1); }
cannam@149 383 };
cannam@149 384 template <typename T, typename U>
cannam@149 385 struct Unit_<Quantity<T, U>> {
cannam@149 386 static inline constexpr Quantity<decltype(Unit_<T>::get()), U> get() {
cannam@149 387 return Quantity<decltype(Unit_<T>::get()), U>(Unit_<T>::get(), unsafe);
cannam@149 388 }
cannam@149 389 };
cannam@149 390
cannam@149 391 template <typename T>
cannam@149 392 inline constexpr auto unit() -> decltype(Unit_<T>::get()) { return Unit_<T>::get(); }
cannam@149 393 // unit<Quantity<T, U>>() returns a Quantity of value 1. It also, intentionally, works on basic
cannam@149 394 // numeric types.
cannam@149 395
cannam@149 396 template <typename Number1, typename Number2, typename Unit>
cannam@149 397 inline constexpr auto operator*(Number1 a, Quantity<Number2, Unit> b)
cannam@149 398 -> Quantity<decltype(Number1() * Number2()), Unit> {
cannam@149 399 return Quantity<decltype(Number1() * Number2()), Unit>(a * b.value, unsafe);
cannam@149 400 }
cannam@149 401
cannam@149 402 template <typename Number1, typename Number2, typename Unit, typename Unit2>
cannam@149 403 inline constexpr auto operator*(UnitRatio<Number1, Unit2, Unit> ratio,
cannam@149 404 Quantity<Number2, Unit> measure)
cannam@149 405 -> decltype(measure * ratio) {
cannam@149 406 return measure * ratio;
cannam@149 407 }
cannam@149 408
cannam@149 409 // =======================================================================================
cannam@149 410 // Absolute measures
cannam@149 411
cannam@149 412 template <typename T, typename Label>
cannam@149 413 class Absolute {
cannam@149 414 // Wraps some other value -- typically a Quantity -- but represents a value measured based on
cannam@149 415 // some absolute origin. For example, if `Duration` is a type representing a time duration,
cannam@149 416 // Absolute<Duration, UnixEpoch> might be a calendar date.
cannam@149 417 //
cannam@149 418 // Since Absolute represents measurements relative to some arbitrary origin, the only sensible
cannam@149 419 // arithmetic to perform on them is addition and subtraction.
cannam@149 420
cannam@149 421 // TODO(someday): Do the same automatic expansion of integer width that Quantity does? Doesn't
cannam@149 422 // matter for our time use case, where we always use 64-bit anyway. Note that fixing this
cannam@149 423 // would implicitly allow things like multiplying an Absolute by a UnitRatio to change its
cannam@149 424 // units, which is actually totally logical and kind of neat.
cannam@149 425
cannam@149 426 public:
cannam@149 427 inline constexpr Absolute operator+(const T& other) const { return Absolute(value + other); }
cannam@149 428 inline constexpr Absolute operator-(const T& other) const { return Absolute(value - other); }
cannam@149 429 inline constexpr T operator-(const Absolute& other) const { return value - other.value; }
cannam@149 430
cannam@149 431 inline Absolute& operator+=(const T& other) { value += other; return *this; }
cannam@149 432 inline Absolute& operator-=(const T& other) { value -= other; return *this; }
cannam@149 433
cannam@149 434 inline constexpr bool operator==(const Absolute& other) const { return value == other.value; }
cannam@149 435 inline constexpr bool operator!=(const Absolute& other) const { return value != other.value; }
cannam@149 436 inline constexpr bool operator<=(const Absolute& other) const { return value <= other.value; }
cannam@149 437 inline constexpr bool operator>=(const Absolute& other) const { return value >= other.value; }
cannam@149 438 inline constexpr bool operator< (const Absolute& other) const { return value < other.value; }
cannam@149 439 inline constexpr bool operator> (const Absolute& other) const { return value > other.value; }
cannam@149 440
cannam@149 441 private:
cannam@149 442 T value;
cannam@149 443
cannam@149 444 explicit constexpr Absolute(T value): value(value) {}
cannam@149 445
cannam@149 446 template <typename U>
cannam@149 447 friend inline constexpr U origin();
cannam@149 448 };
cannam@149 449
cannam@149 450 template <typename T, typename Label>
cannam@149 451 inline constexpr Absolute<T, Label> operator+(const T& a, const Absolute<T, Label>& b) {
cannam@149 452 return b + a;
cannam@149 453 }
cannam@149 454
cannam@149 455 template <typename T> struct UnitOf_ { typedef T Type; };
cannam@149 456 template <typename T, typename Label> struct UnitOf_<Absolute<T, Label>> { typedef T Type; };
cannam@149 457 template <typename T>
cannam@149 458 using UnitOf = typename UnitOf_<T>::Type;
cannam@149 459 // UnitOf<Absolute<T, U>> is T. UnitOf<AnythingElse> is AnythingElse.
cannam@149 460
cannam@149 461 template <typename T>
cannam@149 462 inline constexpr T origin() { return T(0 * unit<UnitOf<T>>()); }
cannam@149 463 // origin<Absolute<T, U>>() returns an Absolute of value 0. It also, intentionally, works on basic
cannam@149 464 // numeric types.
cannam@149 465
cannam@149 466 // =======================================================================================
cannam@149 467 // Overflow avoidance
cannam@149 468
cannam@149 469 template <uint64_t n, uint accum = 0>
cannam@149 470 struct BitCount_ {
cannam@149 471 static constexpr uint value = BitCount_<(n >> 1), accum + 1>::value;
cannam@149 472 };
cannam@149 473 template <uint accum>
cannam@149 474 struct BitCount_<0, accum> {
cannam@149 475 static constexpr uint value = accum;
cannam@149 476 };
cannam@149 477
cannam@149 478 template <uint64_t n>
cannam@149 479 inline constexpr uint bitCount() { return BitCount_<n>::value; }
cannam@149 480 // Number of bits required to represent the number `n`.
cannam@149 481
cannam@149 482 template <uint bitCountBitCount> struct AtLeastUInt_ {
cannam@149 483 static_assert(bitCountBitCount < 7, "don't know how to represent integers over 64 bits");
cannam@149 484 };
cannam@149 485 template <> struct AtLeastUInt_<0> { typedef uint8_t Type; };
cannam@149 486 template <> struct AtLeastUInt_<1> { typedef uint8_t Type; };
cannam@149 487 template <> struct AtLeastUInt_<2> { typedef uint8_t Type; };
cannam@149 488 template <> struct AtLeastUInt_<3> { typedef uint8_t Type; };
cannam@149 489 template <> struct AtLeastUInt_<4> { typedef uint16_t Type; };
cannam@149 490 template <> struct AtLeastUInt_<5> { typedef uint32_t Type; };
cannam@149 491 template <> struct AtLeastUInt_<6> { typedef uint64_t Type; };
cannam@149 492
cannam@149 493 template <uint bits>
cannam@149 494 using AtLeastUInt = typename AtLeastUInt_<bitCount<max(bits, 1) - 1>()>::Type;
cannam@149 495 // AtLeastUInt<n> is an unsigned integer of at least n bits. E.g. AtLeastUInt<12> is uint16_t.
cannam@149 496
cannam@149 497 // -------------------------------------------------------------------
cannam@149 498
cannam@149 499 template <uint value>
cannam@149 500 class BoundedConst {
cannam@149 501 // A constant integer value on which we can do bit size analysis.
cannam@149 502
cannam@149 503 public:
cannam@149 504 BoundedConst() = default;
cannam@149 505
cannam@149 506 inline constexpr uint unwrap() const { return value; }
cannam@149 507
cannam@149 508 #define OP(op, check) \
cannam@149 509 template <uint other> \
cannam@149 510 inline constexpr BoundedConst<(value op other)> \
cannam@149 511 operator op(BoundedConst<other>) const { \
cannam@149 512 static_assert(check, "overflow in BoundedConst arithmetic"); \
cannam@149 513 return BoundedConst<(value op other)>(); \
cannam@149 514 }
cannam@149 515 #define COMPARE_OP(op) \
cannam@149 516 template <uint other> \
cannam@149 517 inline constexpr bool operator op(BoundedConst<other>) const { \
cannam@149 518 return value op other; \
cannam@149 519 }
cannam@149 520
cannam@149 521 OP(+, value + other >= value)
cannam@149 522 OP(-, value - other <= value)
cannam@149 523 OP(*, value * other / other == value)
cannam@149 524 OP(/, true) // div by zero already errors out; no other division ever overflows
cannam@149 525 OP(%, true) // mod by zero already errors out; no other modulus ever overflows
cannam@149 526 OP(<<, value << other >= value)
cannam@149 527 OP(>>, true) // right shift can't overflow
cannam@149 528 OP(&, true) // bitwise ops can't overflow
cannam@149 529 OP(|, true) // bitwise ops can't overflow
cannam@149 530
cannam@149 531 COMPARE_OP(==)
cannam@149 532 COMPARE_OP(!=)
cannam@149 533 COMPARE_OP(< )
cannam@149 534 COMPARE_OP(> )
cannam@149 535 COMPARE_OP(<=)
cannam@149 536 COMPARE_OP(>=)
cannam@149 537 #undef OP
cannam@149 538 #undef COMPARE_OP
cannam@149 539 };
cannam@149 540
cannam@149 541 template <uint64_t m, typename T>
cannam@149 542 struct Unit_<Bounded<m, T>> {
cannam@149 543 static inline constexpr BoundedConst<1> get() { return BoundedConst<1>(); }
cannam@149 544 };
cannam@149 545
cannam@149 546 template <uint value>
cannam@149 547 struct Unit_<BoundedConst<value>> {
cannam@149 548 static inline constexpr BoundedConst<1> get() { return BoundedConst<1>(); }
cannam@149 549 };
cannam@149 550
cannam@149 551 template <uint value>
cannam@149 552 inline constexpr BoundedConst<value> bounded() {
cannam@149 553 return BoundedConst<value>();
cannam@149 554 }
cannam@149 555
cannam@149 556 template <uint64_t a, uint64_t b>
cannam@149 557 static constexpr uint64_t boundedAdd() {
cannam@149 558 static_assert(a + b >= a, "possible overflow detected");
cannam@149 559 return a + b;
cannam@149 560 }
cannam@149 561 template <uint64_t a, uint64_t b>
cannam@149 562 static constexpr uint64_t boundedSub() {
cannam@149 563 static_assert(a - b <= a, "possible underflow detected");
cannam@149 564 return a - b;
cannam@149 565 }
cannam@149 566 template <uint64_t a, uint64_t b>
cannam@149 567 static constexpr uint64_t boundedMul() {
cannam@149 568 static_assert(a * b / b == a, "possible overflow detected");
cannam@149 569 return a * b;
cannam@149 570 }
cannam@149 571 template <uint64_t a, uint64_t b>
cannam@149 572 static constexpr uint64_t boundedLShift() {
cannam@149 573 static_assert(a << b >= a, "possible overflow detected");
cannam@149 574 return a << b;
cannam@149 575 }
cannam@149 576
cannam@149 577 template <uint a, uint b>
cannam@149 578 inline constexpr BoundedConst<kj::min(a, b)> min(BoundedConst<a>, BoundedConst<b>) {
cannam@149 579 return bounded<kj::min(a, b)>();
cannam@149 580 }
cannam@149 581 template <uint a, uint b>
cannam@149 582 inline constexpr BoundedConst<kj::max(a, b)> max(BoundedConst<a>, BoundedConst<b>) {
cannam@149 583 return bounded<kj::max(a, b)>();
cannam@149 584 }
cannam@149 585 // We need to override min() and max() between constants because the ternary operator in the
cannam@149 586 // default implementation would complain.
cannam@149 587
cannam@149 588 // -------------------------------------------------------------------
cannam@149 589
cannam@149 590 template <uint64_t maxN, typename T>
cannam@149 591 class Bounded {
cannam@149 592 public:
cannam@149 593 static_assert(maxN <= T(kj::maxValue), "possible overflow detected");
cannam@149 594
cannam@149 595 Bounded() = default;
cannam@149 596
cannam@149 597 Bounded(const Bounded& other) = default;
cannam@149 598 template <typename OtherInt, typename = EnableIf<isIntegral<OtherInt>()>>
cannam@149 599 inline constexpr Bounded(OtherInt value): value(value) {
cannam@149 600 static_assert(OtherInt(maxValue) <= maxN, "possible overflow detected");
cannam@149 601 }
cannam@149 602 template <uint64_t otherMax, typename OtherT>
cannam@149 603 inline constexpr Bounded(const Bounded<otherMax, OtherT>& other)
cannam@149 604 : value(other.value) {
cannam@149 605 static_assert(otherMax <= maxN, "possible overflow detected");
cannam@149 606 }
cannam@149 607 template <uint otherValue>
cannam@149 608 inline constexpr Bounded(BoundedConst<otherValue>)
cannam@149 609 : value(otherValue) {
cannam@149 610 static_assert(otherValue <= maxN, "overflow detected");
cannam@149 611 }
cannam@149 612
cannam@149 613 Bounded& operator=(const Bounded& other) = default;
cannam@149 614 template <typename OtherInt, typename = EnableIf<isIntegral<OtherInt>()>>
cannam@149 615 Bounded& operator=(OtherInt other) {
cannam@149 616 static_assert(OtherInt(maxValue) <= maxN, "possible overflow detected");
cannam@149 617 value = other;
cannam@149 618 return *this;
cannam@149 619 }
cannam@149 620 template <uint64_t otherMax, typename OtherT>
cannam@149 621 inline Bounded& operator=(const Bounded<otherMax, OtherT>& other) {
cannam@149 622 static_assert(otherMax <= maxN, "possible overflow detected");
cannam@149 623 value = other.value;
cannam@149 624 return *this;
cannam@149 625 }
cannam@149 626 template <uint otherValue>
cannam@149 627 inline Bounded& operator=(BoundedConst<otherValue>) {
cannam@149 628 static_assert(otherValue <= maxN, "overflow detected");
cannam@149 629 value = otherValue;
cannam@149 630 return *this;
cannam@149 631 }
cannam@149 632
cannam@149 633 inline constexpr T unwrap() const { return value; }
cannam@149 634
cannam@149 635 #define OP(op, newMax) \
cannam@149 636 template <uint64_t otherMax, typename otherT> \
cannam@149 637 inline constexpr Bounded<newMax, decltype(T() op otherT())> \
cannam@149 638 operator op(const Bounded<otherMax, otherT>& other) const { \
cannam@149 639 return Bounded<newMax, decltype(T() op otherT())>(value op other.value, unsafe); \
cannam@149 640 }
cannam@149 641 #define COMPARE_OP(op) \
cannam@149 642 template <uint64_t otherMax, typename OtherT> \
cannam@149 643 inline constexpr bool operator op(const Bounded<otherMax, OtherT>& other) const { \
cannam@149 644 return value op other.value; \
cannam@149 645 }
cannam@149 646
cannam@149 647 OP(+, (boundedAdd<maxN, otherMax>()))
cannam@149 648 OP(*, (boundedMul<maxN, otherMax>()))
cannam@149 649 OP(/, maxN)
cannam@149 650 OP(%, otherMax - 1)
cannam@149 651
cannam@149 652 // operator- is intentionally omitted because we mostly use this with unsigned types, and
cannam@149 653 // subtraction requires proof that subtrahend is not greater than the minuend.
cannam@149 654
cannam@149 655 COMPARE_OP(==)
cannam@149 656 COMPARE_OP(!=)
cannam@149 657 COMPARE_OP(< )
cannam@149 658 COMPARE_OP(> )
cannam@149 659 COMPARE_OP(<=)
cannam@149 660 COMPARE_OP(>=)
cannam@149 661
cannam@149 662 #undef OP
cannam@149 663 #undef COMPARE_OP
cannam@149 664
cannam@149 665 template <uint64_t newMax, typename ErrorFunc>
cannam@149 666 inline Bounded<newMax, T> assertMax(ErrorFunc&& func) const {
cannam@149 667 // Assert that the number is no more than `newMax`. Otherwise, call `func`.
cannam@149 668 static_assert(newMax < maxN, "this bounded size assertion is redundant");
cannam@149 669 if (KJ_UNLIKELY(value > newMax)) func();
cannam@149 670 return Bounded<newMax, T>(value, unsafe);
cannam@149 671 }
cannam@149 672
cannam@149 673 template <uint64_t otherMax, typename OtherT, typename ErrorFunc>
cannam@149 674 inline Bounded<maxN, decltype(T() - OtherT())> subtractChecked(
cannam@149 675 const Bounded<otherMax, OtherT>& other, ErrorFunc&& func) const {
cannam@149 676 // Subtract a number, calling func() if the result would underflow.
cannam@149 677 if (KJ_UNLIKELY(value < other.value)) func();
cannam@149 678 return Bounded<maxN, decltype(T() - OtherT())>(value - other.value, unsafe);
cannam@149 679 }
cannam@149 680
cannam@149 681 template <uint otherValue, typename ErrorFunc>
cannam@149 682 inline Bounded<maxN - otherValue, T> subtractChecked(
cannam@149 683 BoundedConst<otherValue>, ErrorFunc&& func) const {
cannam@149 684 // Subtract a number, calling func() if the result would underflow.
cannam@149 685 static_assert(otherValue <= maxN, "underflow detected");
cannam@149 686 if (KJ_UNLIKELY(value < otherValue)) func();
cannam@149 687 return Bounded<maxN - otherValue, T>(value - otherValue, unsafe);
cannam@149 688 }
cannam@149 689
cannam@149 690 template <uint64_t otherMax, typename OtherT>
cannam@149 691 inline Maybe<Bounded<maxN, decltype(T() - OtherT())>> trySubtract(
cannam@149 692 const Bounded<otherMax, OtherT>& other) const {
cannam@149 693 // Subtract a number, calling func() if the result would underflow.
cannam@149 694 if (value < other.value) {
cannam@149 695 return nullptr;
cannam@149 696 } else {
cannam@149 697 return Bounded<maxN, decltype(T() - OtherT())>(value - other.value, unsafe);
cannam@149 698 }
cannam@149 699 }
cannam@149 700
cannam@149 701 template <uint otherValue>
cannam@149 702 inline Maybe<Bounded<maxN - otherValue, T>> trySubtract(BoundedConst<otherValue>) const {
cannam@149 703 // Subtract a number, calling func() if the result would underflow.
cannam@149 704 if (value < otherValue) {
cannam@149 705 return nullptr;
cannam@149 706 } else {
cannam@149 707 return Bounded<maxN - otherValue, T>(value - otherValue, unsafe);
cannam@149 708 }
cannam@149 709 }
cannam@149 710
cannam@149 711 inline constexpr Bounded(T value, decltype(unsafe)): value(value) {}
cannam@149 712 template <uint64_t otherMax, typename OtherT>
cannam@149 713 inline constexpr Bounded(Bounded<otherMax, OtherT> value, decltype(unsafe))
cannam@149 714 : value(value.value) {}
cannam@149 715 // Mainly for internal use.
cannam@149 716 //
cannam@149 717 // Only use these as a last resort, with ample commentary on why you think it's safe.
cannam@149 718
cannam@149 719 private:
cannam@149 720 T value;
cannam@149 721
cannam@149 722 template <uint64_t, typename>
cannam@149 723 friend class Bounded;
cannam@149 724 };
cannam@149 725
cannam@149 726 template <typename Number>
cannam@149 727 inline constexpr Bounded<Number(kj::maxValue), Number> bounded(Number value) {
cannam@149 728 return Bounded<Number(kj::maxValue), Number>(value, unsafe);
cannam@149 729 }
cannam@149 730
cannam@149 731 inline constexpr Bounded<1, uint8_t> bounded(bool value) {
cannam@149 732 return Bounded<1, uint8_t>(value, unsafe);
cannam@149 733 }
cannam@149 734
cannam@149 735 template <uint bits, typename Number>
cannam@149 736 inline constexpr Bounded<maxValueForBits<bits>(), Number> assumeBits(Number value) {
cannam@149 737 return Bounded<maxValueForBits<bits>(), Number>(value, unsafe);
cannam@149 738 }
cannam@149 739
cannam@149 740 template <uint bits, uint64_t maxN, typename T>
cannam@149 741 inline constexpr Bounded<maxValueForBits<bits>(), T> assumeBits(Bounded<maxN, T> value) {
cannam@149 742 return Bounded<maxValueForBits<bits>(), T>(value, unsafe);
cannam@149 743 }
cannam@149 744
cannam@149 745 template <uint bits, typename Number, typename Unit>
cannam@149 746 inline constexpr auto assumeBits(Quantity<Number, Unit> value)
cannam@149 747 -> Quantity<decltype(assumeBits<bits>(value / unit<Quantity<Number, Unit>>())), Unit> {
cannam@149 748 return Quantity<decltype(assumeBits<bits>(value / unit<Quantity<Number, Unit>>())), Unit>(
cannam@149 749 assumeBits<bits>(value / unit<Quantity<Number, Unit>>()), unsafe);
cannam@149 750 }
cannam@149 751
cannam@149 752 template <uint64_t maxN, typename Number>
cannam@149 753 inline constexpr Bounded<maxN, Number> assumeMax(Number value) {
cannam@149 754 return Bounded<maxN, Number>(value, unsafe);
cannam@149 755 }
cannam@149 756
cannam@149 757 template <uint64_t newMaxN, uint64_t maxN, typename T>
cannam@149 758 inline constexpr Bounded<newMaxN, T> assumeMax(Bounded<maxN, T> value) {
cannam@149 759 return Bounded<newMaxN, T>(value, unsafe);
cannam@149 760 }
cannam@149 761
cannam@149 762 template <uint64_t maxN, typename Number, typename Unit>
cannam@149 763 inline constexpr auto assumeMax(Quantity<Number, Unit> value)
cannam@149 764 -> Quantity<decltype(assumeMax<maxN>(value / unit<Quantity<Number, Unit>>())), Unit> {
cannam@149 765 return Quantity<decltype(assumeMax<maxN>(value / unit<Quantity<Number, Unit>>())), Unit>(
cannam@149 766 assumeMax<maxN>(value / unit<Quantity<Number, Unit>>()), unsafe);
cannam@149 767 }
cannam@149 768
cannam@149 769 template <uint maxN, typename Number>
cannam@149 770 inline constexpr Bounded<maxN, Number> assumeMax(BoundedConst<maxN>, Number value) {
cannam@149 771 return assumeMax<maxN>(value);
cannam@149 772 }
cannam@149 773
cannam@149 774 template <uint newMaxN, uint64_t maxN, typename T>
cannam@149 775 inline constexpr Bounded<newMaxN, T> assumeMax(BoundedConst<maxN>, Bounded<maxN, T> value) {
cannam@149 776 return assumeMax<maxN>(value);
cannam@149 777 }
cannam@149 778
cannam@149 779 template <uint maxN, typename Number, typename Unit>
cannam@149 780 inline constexpr auto assumeMax(Quantity<BoundedConst<maxN>, Unit>, Quantity<Number, Unit> value)
cannam@149 781 -> decltype(assumeMax<maxN>(value)) {
cannam@149 782 return assumeMax<maxN>(value);
cannam@149 783 }
cannam@149 784
cannam@149 785 template <uint64_t newMax, uint64_t maxN, typename T, typename ErrorFunc>
cannam@149 786 inline Bounded<newMax, T> assertMax(Bounded<maxN, T> value, ErrorFunc&& errorFunc) {
cannam@149 787 // Assert that the bounded value is less than or equal to the given maximum, calling errorFunc()
cannam@149 788 // if not.
cannam@149 789 static_assert(newMax < maxN, "this bounded size assertion is redundant");
cannam@149 790 return value.template assertMax<newMax>(kj::fwd<ErrorFunc>(errorFunc));
cannam@149 791 }
cannam@149 792
cannam@149 793 template <uint64_t newMax, uint64_t maxN, typename T, typename Unit, typename ErrorFunc>
cannam@149 794 inline Quantity<Bounded<newMax, T>, Unit> assertMax(
cannam@149 795 Quantity<Bounded<maxN, T>, Unit> value, ErrorFunc&& errorFunc) {
cannam@149 796 // Assert that the bounded value is less than or equal to the given maximum, calling errorFunc()
cannam@149 797 // if not.
cannam@149 798 static_assert(newMax < maxN, "this bounded size assertion is redundant");
cannam@149 799 return (value / unit<decltype(value)>()).template assertMax<newMax>(
cannam@149 800 kj::fwd<ErrorFunc>(errorFunc)) * unit<decltype(value)>();
cannam@149 801 }
cannam@149 802
cannam@149 803 template <uint newMax, uint64_t maxN, typename T, typename ErrorFunc>
cannam@149 804 inline Bounded<newMax, T> assertMax(
cannam@149 805 BoundedConst<newMax>, Bounded<maxN, T> value, ErrorFunc&& errorFunc) {
cannam@149 806 return assertMax<newMax>(value, kj::mv(errorFunc));
cannam@149 807 }
cannam@149 808
cannam@149 809 template <uint newMax, uint64_t maxN, typename T, typename Unit, typename ErrorFunc>
cannam@149 810 inline Quantity<Bounded<newMax, T>, Unit> assertMax(
cannam@149 811 Quantity<BoundedConst<newMax>, Unit>,
cannam@149 812 Quantity<Bounded<maxN, T>, Unit> value, ErrorFunc&& errorFunc) {
cannam@149 813 return assertMax<newMax>(value, kj::mv(errorFunc));
cannam@149 814 }
cannam@149 815
cannam@149 816 template <uint64_t newBits, uint64_t maxN, typename T, typename ErrorFunc = ThrowOverflow>
cannam@149 817 inline Bounded<maxValueForBits<newBits>(), T> assertMaxBits(
cannam@149 818 Bounded<maxN, T> value, ErrorFunc&& errorFunc = ErrorFunc()) {
cannam@149 819 // Assert that the bounded value requires no more than the given number of bits, calling
cannam@149 820 // errorFunc() if not.
cannam@149 821 return assertMax<maxValueForBits<newBits>()>(value, kj::fwd<ErrorFunc>(errorFunc));
cannam@149 822 }
cannam@149 823
cannam@149 824 template <uint64_t newBits, uint64_t maxN, typename T, typename Unit,
cannam@149 825 typename ErrorFunc = ThrowOverflow>
cannam@149 826 inline Quantity<Bounded<maxValueForBits<newBits>(), T>, Unit> assertMaxBits(
cannam@149 827 Quantity<Bounded<maxN, T>, Unit> value, ErrorFunc&& errorFunc = ErrorFunc()) {
cannam@149 828 // Assert that the bounded value requires no more than the given number of bits, calling
cannam@149 829 // errorFunc() if not.
cannam@149 830 return assertMax<maxValueForBits<newBits>()>(value, kj::fwd<ErrorFunc>(errorFunc));
cannam@149 831 }
cannam@149 832
cannam@149 833 template <typename newT, uint64_t maxN, typename T>
cannam@149 834 inline constexpr Bounded<maxN, newT> upgradeBound(Bounded<maxN, T> value) {
cannam@149 835 return value;
cannam@149 836 }
cannam@149 837
cannam@149 838 template <typename newT, uint64_t maxN, typename T, typename Unit>
cannam@149 839 inline constexpr Quantity<Bounded<maxN, newT>, Unit> upgradeBound(
cannam@149 840 Quantity<Bounded<maxN, T>, Unit> value) {
cannam@149 841 return value;
cannam@149 842 }
cannam@149 843
cannam@149 844 template <uint64_t maxN, typename T, typename Other, typename ErrorFunc>
cannam@149 845 inline auto subtractChecked(Bounded<maxN, T> value, Other other, ErrorFunc&& errorFunc)
cannam@149 846 -> decltype(value.subtractChecked(other, kj::fwd<ErrorFunc>(errorFunc))) {
cannam@149 847 return value.subtractChecked(other, kj::fwd<ErrorFunc>(errorFunc));
cannam@149 848 }
cannam@149 849
cannam@149 850 template <typename T, typename U, typename Unit, typename ErrorFunc>
cannam@149 851 inline auto subtractChecked(Quantity<T, Unit> value, Quantity<U, Unit> other, ErrorFunc&& errorFunc)
cannam@149 852 -> Quantity<decltype(subtractChecked(T(), U(), kj::fwd<ErrorFunc>(errorFunc))), Unit> {
cannam@149 853 return subtractChecked(value / unit<Quantity<T, Unit>>(),
cannam@149 854 other / unit<Quantity<U, Unit>>(),
cannam@149 855 kj::fwd<ErrorFunc>(errorFunc))
cannam@149 856 * unit<Quantity<T, Unit>>();
cannam@149 857 }
cannam@149 858
cannam@149 859 template <uint64_t maxN, typename T, typename Other>
cannam@149 860 inline auto trySubtract(Bounded<maxN, T> value, Other other)
cannam@149 861 -> decltype(value.trySubtract(other)) {
cannam@149 862 return value.trySubtract(other);
cannam@149 863 }
cannam@149 864
cannam@149 865 template <typename T, typename U, typename Unit>
cannam@149 866 inline auto trySubtract(Quantity<T, Unit> value, Quantity<U, Unit> other)
cannam@149 867 -> Maybe<Quantity<decltype(subtractChecked(T(), U(), int())), Unit>> {
cannam@149 868 return trySubtract(value / unit<Quantity<T, Unit>>(),
cannam@149 869 other / unit<Quantity<U, Unit>>())
cannam@149 870 .map([](decltype(subtractChecked(T(), U(), int())) x) {
cannam@149 871 return x * unit<Quantity<T, Unit>>();
cannam@149 872 });
cannam@149 873 }
cannam@149 874
cannam@149 875 template <uint64_t aN, uint64_t bN, typename A, typename B>
cannam@149 876 inline constexpr Bounded<kj::min(aN, bN), WiderType<A, B>>
cannam@149 877 min(Bounded<aN, A> a, Bounded<bN, B> b) {
cannam@149 878 return Bounded<kj::min(aN, bN), WiderType<A, B>>(kj::min(a.unwrap(), b.unwrap()), unsafe);
cannam@149 879 }
cannam@149 880 template <uint64_t aN, uint64_t bN, typename A, typename B>
cannam@149 881 inline constexpr Bounded<kj::max(aN, bN), WiderType<A, B>>
cannam@149 882 max(Bounded<aN, A> a, Bounded<bN, B> b) {
cannam@149 883 return Bounded<kj::max(aN, bN), WiderType<A, B>>(kj::max(a.unwrap(), b.unwrap()), unsafe);
cannam@149 884 }
cannam@149 885 // We need to override min() and max() because:
cannam@149 886 // 1) WiderType<> might not choose the correct bounds.
cannam@149 887 // 2) One of the two sides of the ternary operator in the default implementation would fail to
cannam@149 888 // typecheck even though it is OK in practice.
cannam@149 889
cannam@149 890 // -------------------------------------------------------------------
cannam@149 891 // Operators between Bounded and BoundedConst
cannam@149 892
cannam@149 893 #define OP(op, newMax) \
cannam@149 894 template <uint64_t maxN, uint cvalue, typename T> \
cannam@149 895 inline constexpr Bounded<(newMax), decltype(T() op uint())> operator op( \
cannam@149 896 Bounded<maxN, T> value, BoundedConst<cvalue>) { \
cannam@149 897 return Bounded<(newMax), decltype(T() op uint())>(value.unwrap() op cvalue, unsafe); \
cannam@149 898 }
cannam@149 899
cannam@149 900 #define REVERSE_OP(op, newMax) \
cannam@149 901 template <uint64_t maxN, uint cvalue, typename T> \
cannam@149 902 inline constexpr Bounded<(newMax), decltype(uint() op T())> operator op( \
cannam@149 903 BoundedConst<cvalue>, Bounded<maxN, T> value) { \
cannam@149 904 return Bounded<(newMax), decltype(uint() op T())>(cvalue op value.unwrap(), unsafe); \
cannam@149 905 }
cannam@149 906
cannam@149 907 #define COMPARE_OP(op) \
cannam@149 908 template <uint64_t maxN, uint cvalue, typename T> \
cannam@149 909 inline constexpr bool operator op(Bounded<maxN, T> value, BoundedConst<cvalue>) { \
cannam@149 910 return value.unwrap() op cvalue; \
cannam@149 911 } \
cannam@149 912 template <uint64_t maxN, uint cvalue, typename T> \
cannam@149 913 inline constexpr bool operator op(BoundedConst<cvalue>, Bounded<maxN, T> value) { \
cannam@149 914 return cvalue op value.unwrap(); \
cannam@149 915 }
cannam@149 916
cannam@149 917 OP(+, (boundedAdd<maxN, cvalue>()))
cannam@149 918 REVERSE_OP(+, (boundedAdd<maxN, cvalue>()))
cannam@149 919
cannam@149 920 OP(*, (boundedMul<maxN, cvalue>()))
cannam@149 921 REVERSE_OP(*, (boundedAdd<maxN, cvalue>()))
cannam@149 922
cannam@149 923 OP(/, maxN / cvalue)
cannam@149 924 REVERSE_OP(/, cvalue) // denominator could be 1
cannam@149 925
cannam@149 926 OP(%, cvalue - 1)
cannam@149 927 REVERSE_OP(%, maxN - 1)
cannam@149 928
cannam@149 929 OP(<<, (boundedLShift<maxN, cvalue>()))
cannam@149 930 REVERSE_OP(<<, (boundedLShift<cvalue, maxN>()))
cannam@149 931
cannam@149 932 OP(>>, maxN >> cvalue)
cannam@149 933 REVERSE_OP(>>, cvalue >> maxN)
cannam@149 934
cannam@149 935 OP(&, maxValueForBits<bitCount<maxN>()>() & cvalue)
cannam@149 936 REVERSE_OP(&, maxValueForBits<bitCount<maxN>()>() & cvalue)
cannam@149 937
cannam@149 938 OP(|, maxN | cvalue)
cannam@149 939 REVERSE_OP(|, maxN | cvalue)
cannam@149 940
cannam@149 941 COMPARE_OP(==)
cannam@149 942 COMPARE_OP(!=)
cannam@149 943 COMPARE_OP(< )
cannam@149 944 COMPARE_OP(> )
cannam@149 945 COMPARE_OP(<=)
cannam@149 946 COMPARE_OP(>=)
cannam@149 947
cannam@149 948 #undef OP
cannam@149 949 #undef REVERSE_OP
cannam@149 950 #undef COMPARE_OP
cannam@149 951
cannam@149 952 template <uint64_t maxN, uint cvalue, typename T>
cannam@149 953 inline constexpr Bounded<cvalue, decltype(uint() - T())>
cannam@149 954 operator-(BoundedConst<cvalue>, Bounded<maxN, T> value) {
cannam@149 955 // We allow subtraction of a variable from a constant only if the constant is greater than or
cannam@149 956 // equal to the maximum possible value of the variable. Since the variable could be zero, the
cannam@149 957 // result can be as large as the constant.
cannam@149 958 //
cannam@149 959 // We do not allow subtraction of a constant from a variable because there's never a guarantee it
cannam@149 960 // won't underflow (unless the constant is zero, which is silly).
cannam@149 961 static_assert(cvalue >= maxN, "possible underflow detected");
cannam@149 962 return Bounded<cvalue, decltype(uint() - T())>(cvalue - value.unwrap(), unsafe);
cannam@149 963 }
cannam@149 964
cannam@149 965 template <uint64_t aN, uint b, typename A>
cannam@149 966 inline constexpr Bounded<kj::min(aN, b), A> min(Bounded<aN, A> a, BoundedConst<b>) {
cannam@149 967 return Bounded<kj::min(aN, b), A>(kj::min(b, a.unwrap()), unsafe);
cannam@149 968 }
cannam@149 969 template <uint64_t aN, uint b, typename A>
cannam@149 970 inline constexpr Bounded<kj::min(aN, b), A> min(BoundedConst<b>, Bounded<aN, A> a) {
cannam@149 971 return Bounded<kj::min(aN, b), A>(kj::min(a.unwrap(), b), unsafe);
cannam@149 972 }
cannam@149 973 template <uint64_t aN, uint b, typename A>
cannam@149 974 inline constexpr Bounded<kj::max(aN, b), A> max(Bounded<aN, A> a, BoundedConst<b>) {
cannam@149 975 return Bounded<kj::max(aN, b), A>(kj::max(b, a.unwrap()), unsafe);
cannam@149 976 }
cannam@149 977 template <uint64_t aN, uint b, typename A>
cannam@149 978 inline constexpr Bounded<kj::max(aN, b), A> max(BoundedConst<b>, Bounded<aN, A> a) {
cannam@149 979 return Bounded<kj::max(aN, b), A>(kj::max(a.unwrap(), b), unsafe);
cannam@149 980 }
cannam@149 981 // We need to override min() between a Bounded and a constant since:
cannam@149 982 // 1) WiderType<> might choose BoundedConst over a 1-byte Bounded, which is wrong.
cannam@149 983 // 2) To clamp the bounds of the output type.
cannam@149 984 // 3) Same ternary operator typechecking issues.
cannam@149 985
cannam@149 986 // -------------------------------------------------------------------
cannam@149 987
cannam@149 988 template <uint64_t maxN, typename T>
cannam@149 989 class SafeUnwrapper {
cannam@149 990 public:
cannam@149 991 inline explicit constexpr SafeUnwrapper(Bounded<maxN, T> value): value(value.unwrap()) {}
cannam@149 992
cannam@149 993 template <typename U, typename = EnableIf<isIntegral<U>()>>
cannam@149 994 inline constexpr operator U() const {
cannam@149 995 static_assert(maxN <= U(maxValue), "possible truncation detected");
cannam@149 996 return value;
cannam@149 997 }
cannam@149 998
cannam@149 999 inline constexpr operator bool() const {
cannam@149 1000 static_assert(maxN <= 1, "possible truncation detected");
cannam@149 1001 return value;
cannam@149 1002 }
cannam@149 1003
cannam@149 1004 private:
cannam@149 1005 T value;
cannam@149 1006 };
cannam@149 1007
cannam@149 1008 template <uint64_t maxN, typename T>
cannam@149 1009 inline constexpr SafeUnwrapper<maxN, T> unbound(Bounded<maxN, T> bounded) {
cannam@149 1010 // Unwraps the bounded value, returning a value that can be implicitly cast to any integer type.
cannam@149 1011 // If this implicit cast could truncate, a compile-time error will be raised.
cannam@149 1012 return SafeUnwrapper<maxN, T>(bounded);
cannam@149 1013 }
cannam@149 1014
cannam@149 1015 template <uint64_t value>
cannam@149 1016 class SafeConstUnwrapper {
cannam@149 1017 public:
cannam@149 1018 template <typename T, typename = EnableIf<isIntegral<T>()>>
cannam@149 1019 inline constexpr operator T() const {
cannam@149 1020 static_assert(value <= T(maxValue), "this operation will truncate");
cannam@149 1021 return value;
cannam@149 1022 }
cannam@149 1023
cannam@149 1024 inline constexpr operator bool() const {
cannam@149 1025 static_assert(value <= 1, "this operation will truncate");
cannam@149 1026 return value;
cannam@149 1027 }
cannam@149 1028 };
cannam@149 1029
cannam@149 1030 template <uint value>
cannam@149 1031 inline constexpr SafeConstUnwrapper<value> unbound(BoundedConst<value>) {
cannam@149 1032 return SafeConstUnwrapper<value>();
cannam@149 1033 }
cannam@149 1034
cannam@149 1035 template <typename T, typename U>
cannam@149 1036 inline constexpr T unboundAs(U value) {
cannam@149 1037 return unbound(value);
cannam@149 1038 }
cannam@149 1039
cannam@149 1040 template <uint64_t requestedMax, uint64_t maxN, typename T>
cannam@149 1041 inline constexpr T unboundMax(Bounded<maxN, T> value) {
cannam@149 1042 // Explicitly ungaurd expecting a value that is at most `maxN`.
cannam@149 1043 static_assert(maxN <= requestedMax, "possible overflow detected");
cannam@149 1044 return value.unwrap();
cannam@149 1045 }
cannam@149 1046
cannam@149 1047 template <uint64_t requestedMax, uint value>
cannam@149 1048 inline constexpr uint unboundMax(BoundedConst<value>) {
cannam@149 1049 // Explicitly ungaurd expecting a value that is at most `maxN`.
cannam@149 1050 static_assert(value <= requestedMax, "overflow detected");
cannam@149 1051 return value;
cannam@149 1052 }
cannam@149 1053
cannam@149 1054 template <uint bits, typename T>
cannam@149 1055 inline constexpr auto unboundMaxBits(T value) ->
cannam@149 1056 decltype(unboundMax<maxValueForBits<bits>()>(value)) {
cannam@149 1057 // Explicitly ungaurd expecting a value that fits into `bits` bits.
cannam@149 1058 return unboundMax<maxValueForBits<bits>()>(value);
cannam@149 1059 }
cannam@149 1060
cannam@149 1061 #define OP(op) \
cannam@149 1062 template <uint64_t maxN, typename T, typename U> \
cannam@149 1063 inline constexpr auto operator op(T a, SafeUnwrapper<maxN, U> b) -> decltype(a op (T)b) { \
cannam@149 1064 return a op (AtLeastUInt<sizeof(T)*8>)b; \
cannam@149 1065 } \
cannam@149 1066 template <uint64_t maxN, typename T, typename U> \
cannam@149 1067 inline constexpr auto operator op(SafeUnwrapper<maxN, U> b, T a) -> decltype((T)b op a) { \
cannam@149 1068 return (AtLeastUInt<sizeof(T)*8>)b op a; \
cannam@149 1069 } \
cannam@149 1070 template <uint64_t value, typename T> \
cannam@149 1071 inline constexpr auto operator op(T a, SafeConstUnwrapper<value> b) -> decltype(a op (T)b) { \
cannam@149 1072 return a op (AtLeastUInt<sizeof(T)*8>)b; \
cannam@149 1073 } \
cannam@149 1074 template <uint64_t value, typename T> \
cannam@149 1075 inline constexpr auto operator op(SafeConstUnwrapper<value> b, T a) -> decltype((T)b op a) { \
cannam@149 1076 return (AtLeastUInt<sizeof(T)*8>)b op a; \
cannam@149 1077 }
cannam@149 1078
cannam@149 1079 OP(+)
cannam@149 1080 OP(-)
cannam@149 1081 OP(*)
cannam@149 1082 OP(/)
cannam@149 1083 OP(%)
cannam@149 1084 OP(<<)
cannam@149 1085 OP(>>)
cannam@149 1086 OP(&)
cannam@149 1087 OP(|)
cannam@149 1088 OP(==)
cannam@149 1089 OP(!=)
cannam@149 1090 OP(<=)
cannam@149 1091 OP(>=)
cannam@149 1092 OP(<)
cannam@149 1093 OP(>)
cannam@149 1094
cannam@149 1095 #undef OP
cannam@149 1096
cannam@149 1097 // -------------------------------------------------------------------
cannam@149 1098
cannam@149 1099 template <uint64_t maxN, typename T>
cannam@149 1100 class Range<Bounded<maxN, T>> {
cannam@149 1101 public:
cannam@149 1102 inline constexpr Range(Bounded<maxN, T> begin, Bounded<maxN, T> end)
cannam@149 1103 : inner(unbound(begin), unbound(end)) {}
cannam@149 1104 inline explicit constexpr Range(Bounded<maxN, T> end)
cannam@149 1105 : inner(unbound(end)) {}
cannam@149 1106
cannam@149 1107 class Iterator {
cannam@149 1108 public:
cannam@149 1109 Iterator() = default;
cannam@149 1110 inline explicit Iterator(typename Range<T>::Iterator inner): inner(inner) {}
cannam@149 1111
cannam@149 1112 inline Bounded<maxN, T> operator* () const { return Bounded<maxN, T>(*inner, unsafe); }
cannam@149 1113 inline Iterator& operator++() { ++inner; return *this; }
cannam@149 1114
cannam@149 1115 inline bool operator==(const Iterator& other) const { return inner == other.inner; }
cannam@149 1116 inline bool operator!=(const Iterator& other) const { return inner != other.inner; }
cannam@149 1117
cannam@149 1118 private:
cannam@149 1119 typename Range<T>::Iterator inner;
cannam@149 1120 };
cannam@149 1121
cannam@149 1122 inline Iterator begin() const { return Iterator(inner.begin()); }
cannam@149 1123 inline Iterator end() const { return Iterator(inner.end()); }
cannam@149 1124
cannam@149 1125 private:
cannam@149 1126 Range<T> inner;
cannam@149 1127 };
cannam@149 1128
cannam@149 1129 template <typename T, typename U>
cannam@149 1130 class Range<Quantity<T, U>> {
cannam@149 1131 public:
cannam@149 1132 inline constexpr Range(Quantity<T, U> begin, Quantity<T, U> end)
cannam@149 1133 : inner(begin / unit<Quantity<T, U>>(), end / unit<Quantity<T, U>>()) {}
cannam@149 1134 inline explicit constexpr Range(Quantity<T, U> end)
cannam@149 1135 : inner(end / unit<Quantity<T, U>>()) {}
cannam@149 1136
cannam@149 1137 class Iterator {
cannam@149 1138 public:
cannam@149 1139 Iterator() = default;
cannam@149 1140 inline explicit Iterator(typename Range<T>::Iterator inner): inner(inner) {}
cannam@149 1141
cannam@149 1142 inline Quantity<T, U> operator* () const { return *inner * unit<Quantity<T, U>>(); }
cannam@149 1143 inline Iterator& operator++() { ++inner; return *this; }
cannam@149 1144
cannam@149 1145 inline bool operator==(const Iterator& other) const { return inner == other.inner; }
cannam@149 1146 inline bool operator!=(const Iterator& other) const { return inner != other.inner; }
cannam@149 1147
cannam@149 1148 private:
cannam@149 1149 typename Range<T>::Iterator inner;
cannam@149 1150 };
cannam@149 1151
cannam@149 1152 inline Iterator begin() const { return Iterator(inner.begin()); }
cannam@149 1153 inline Iterator end() const { return Iterator(inner.end()); }
cannam@149 1154
cannam@149 1155 private:
cannam@149 1156 Range<T> inner;
cannam@149 1157 };
cannam@149 1158
cannam@149 1159 template <uint value>
cannam@149 1160 inline constexpr Range<Bounded<value, uint>> zeroTo(BoundedConst<value> end) {
cannam@149 1161 return Range<Bounded<value, uint>>(end);
cannam@149 1162 }
cannam@149 1163
cannam@149 1164 template <uint value, typename Unit>
cannam@149 1165 inline constexpr Range<Quantity<Bounded<value, uint>, Unit>>
cannam@149 1166 zeroTo(Quantity<BoundedConst<value>, Unit> end) {
cannam@149 1167 return Range<Quantity<Bounded<value, uint>, Unit>>(end);
cannam@149 1168 }
cannam@149 1169
cannam@149 1170 } // namespace kj
cannam@149 1171
cannam@149 1172 #endif // KJ_UNITS_H_