annotate win64-msvc/include/kj/units.h @ 64:eccd51b72864

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