annotate osx/include/kj/units.h @ 169:223a55898ab9 tip default

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