annotate win32-mingw/include/kj/units.h @ 70:9e21af8f0420

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