units.h 44.9 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21 22 23 24 25

// This file contains types which are intended to help detect incorrect usage at compile
// time, but should then be optimized down to basic primitives (usually, integers) by the
// compiler.

26
#pragma once
27

28 29 30 31
#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
#pragma GCC system_header
#endif

Kenton Varda's avatar
Kenton Varda committed
32
#include "common.h"
33
#include <inttypes.h>
34

35
namespace kj {
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

// =======================================================================================
// IDs

template <typename UnderlyingType, typename Label>
struct Id {
  // A type-safe numeric ID.  `UnderlyingType` is the underlying integer representation.  `Label`
  // distinguishes this Id from other Id types.  Sample usage:
  //
  //   class Foo;
  //   typedef Id<uint, Foo> FooId;
  //
  //   class Bar;
  //   typedef Id<uint, Bar> BarId;
  //
  // You can now use the FooId and BarId types without any possibility of accidentally using a
  // FooId when you really wanted a BarId or vice-versa.

  UnderlyingType value;

  inline constexpr Id(): value(0) {}
  inline constexpr explicit Id(int value): value(value) {}

59 60 61 62 63 64
  inline constexpr bool operator==(const Id& other) const { return value == other.value; }
  inline constexpr bool operator!=(const Id& other) const { return value != other.value; }
  inline constexpr bool operator<=(const Id& other) const { return value <= other.value; }
  inline constexpr bool operator>=(const Id& other) const { return value >= other.value; }
  inline constexpr bool operator< (const Id& other) const { return value <  other.value; }
  inline constexpr bool operator> (const Id& other) const { return value >  other.value; }
65 66 67
};

// =======================================================================================
Kenton Varda's avatar
Kenton Varda committed
68
// Quantity and UnitRatio -- implement unit analysis via the type system
69

70 71 72 73 74
struct Unsafe_ {};
constexpr Unsafe_ unsafe = Unsafe_();
// Use as a parameter to constructors that are unsafe to indicate that you really do mean it.

template <uint64_t maxN, typename T>
75
class Bounded;
76
template <uint value>
77
class BoundedConst;
78

79 80 81 82 83 84 85 86 87 88 89 90 91
template <typename T> constexpr bool isIntegral() { return false; }
template <> constexpr bool isIntegral<char>() { return true; }
template <> constexpr bool isIntegral<signed char>() { return true; }
template <> constexpr bool isIntegral<short>() { return true; }
template <> constexpr bool isIntegral<int>() { return true; }
template <> constexpr bool isIntegral<long>() { return true; }
template <> constexpr bool isIntegral<long long>() { return true; }
template <> constexpr bool isIntegral<unsigned char>() { return true; }
template <> constexpr bool isIntegral<unsigned short>() { return true; }
template <> constexpr bool isIntegral<unsigned int>() { return true; }
template <> constexpr bool isIntegral<unsigned long>() { return true; }
template <> constexpr bool isIntegral<unsigned long long>() { return true; }

92
template <typename T>
93
struct IsIntegralOrBounded_ { static constexpr bool value = isIntegral<T>(); };
94
template <uint64_t m, typename T>
95
struct IsIntegralOrBounded_<Bounded<m, T>> { static constexpr bool value = true; };
96
template <uint v>
97
struct IsIntegralOrBounded_<BoundedConst<v>> { static constexpr bool value = true; };
98 99

template <typename T>
100
inline constexpr bool isIntegralOrBounded() { return IsIntegralOrBounded_<T>::value; }
101

102 103 104 105 106 107 108 109
template <typename Number, typename Unit1, typename Unit2>
class UnitRatio {
  // A multiplier used to convert Quantities of one unit to Quantities of another unit.  See
  // Quantity, below.
  //
  // Construct this type by dividing one Quantity by another of a different unit.  Use this type
  // by multiplying it by a Quantity, or dividing a Quantity by it.

110
  static_assert(isIntegralOrBounded<Number>(),
111
      "Underlying type for UnitRatio must be integer.");
112

113 114 115
public:
  inline UnitRatio() {}

116
  constexpr UnitRatio(Number unit1PerUnit2, decltype(unsafe)): unit1PerUnit2(unit1PerUnit2) {}
117 118 119
  // This constructor was intended to be private, but GCC complains about it being private in a
  // bunch of places that don't appear to even call it, so I made it public.  Oh well.

120 121 122 123
  template <typename OtherNumber>
  inline constexpr UnitRatio(const UnitRatio<OtherNumber, Unit1, Unit2>& other)
      : unit1PerUnit2(other.unit1PerUnit2) {}

124
  template <typename OtherNumber>
125
  inline constexpr UnitRatio<decltype(Number()+OtherNumber()), Unit1, Unit2>
126
      operator+(UnitRatio<OtherNumber, Unit1, Unit2> other) const {
127 128
    return UnitRatio<decltype(Number()+OtherNumber()), Unit1, Unit2>(
        unit1PerUnit2 + other.unit1PerUnit2, unsafe);
129 130
  }
  template <typename OtherNumber>
131
  inline constexpr UnitRatio<decltype(Number()-OtherNumber()), Unit1, Unit2>
132
      operator-(UnitRatio<OtherNumber, Unit1, Unit2> other) const {
133 134
    return UnitRatio<decltype(Number()-OtherNumber()), Unit1, Unit2>(
        unit1PerUnit2 - other.unit1PerUnit2, unsafe);
135 136
  }

137
  template <typename OtherNumber, typename Unit3>
138
  inline constexpr UnitRatio<decltype(Number()*OtherNumber()), Unit3, Unit2>
139
      operator*(UnitRatio<OtherNumber, Unit3, Unit1> other) const {
140
    // U1 / U2 * U3 / U1 = U3 / U2
141 142
    return UnitRatio<decltype(Number()*OtherNumber()), Unit3, Unit2>(
        unit1PerUnit2 * other.unit1PerUnit2, unsafe);
143 144
  }
  template <typename OtherNumber, typename Unit3>
145
  inline constexpr UnitRatio<decltype(Number()*OtherNumber()), Unit1, Unit3>
146
      operator*(UnitRatio<OtherNumber, Unit2, Unit3> other) const {
147
    // U1 / U2 * U2 / U3 = U1 / U3
148 149
    return UnitRatio<decltype(Number()*OtherNumber()), Unit1, Unit3>(
        unit1PerUnit2 * other.unit1PerUnit2, unsafe);
150 151
  }

152
  template <typename OtherNumber, typename Unit3>
153
  inline constexpr UnitRatio<decltype(Number()*OtherNumber()), Unit3, Unit2>
154
      operator/(UnitRatio<OtherNumber, Unit1, Unit3> other) const {
155
    // (U1 / U2) / (U1 / U3) = U3 / U2
156 157
    return UnitRatio<decltype(Number()*OtherNumber()), Unit3, Unit2>(
        unit1PerUnit2 / other.unit1PerUnit2, unsafe);
158 159
  }
  template <typename OtherNumber, typename Unit3>
160
  inline constexpr UnitRatio<decltype(Number()*OtherNumber()), Unit1, Unit3>
161
      operator/(UnitRatio<OtherNumber, Unit3, Unit2> other) const {
162
    // (U1 / U2) / (U3 / U2) = U1 / U3
163 164
    return UnitRatio<decltype(Number()*OtherNumber()), Unit1, Unit3>(
        unit1PerUnit2 / other.unit1PerUnit2, unsafe);
165 166
  }

167
  template <typename OtherNumber>
168
  inline decltype(Number() / OtherNumber())
169 170 171 172 173 174 175
      operator/(UnitRatio<OtherNumber, Unit1, Unit2> other) const {
    return unit1PerUnit2 / other.unit1PerUnit2;
  }

  inline bool operator==(UnitRatio other) const { return unit1PerUnit2 == other.unit1PerUnit2; }
  inline bool operator!=(UnitRatio other) const { return unit1PerUnit2 != other.unit1PerUnit2; }

176 177 178 179 180 181 182 183
private:
  Number unit1PerUnit2;

  template <typename OtherNumber, typename OtherUnit>
  friend class Quantity;
  template <typename OtherNumber, typename OtherUnit1, typename OtherUnit2>
  friend class UnitRatio;

184
  template <typename N1, typename N2, typename U1, typename U2, typename>
185
  friend inline constexpr UnitRatio<decltype(N1() * N2()), U1, U2>
186
      operator*(N1, UnitRatio<N2, U1, U2>);
187 188
};

189
template <typename N1, typename N2, typename U1, typename U2,
190
          typename = EnableIf<isIntegralOrBounded<N1>() && isIntegralOrBounded<N2>()>>
191
inline constexpr UnitRatio<decltype(N1() * N2()), U1, U2>
192
    operator*(N1 n, UnitRatio<N2, U1, U2> r) {
193
  return UnitRatio<decltype(N1() * N2()), U1, U2>(n * r.unit1PerUnit2, unsafe);
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
}

template <typename Number, typename Unit>
class Quantity {
  // A type-safe numeric quantity, specified in terms of some unit.  Two Quantities cannot be used
  // in arithmetic unless they use the same unit.  The `Unit` type parameter is only used to prevent
  // accidental mixing of units; this type is never instantiated and can very well be incomplete.
  // `Number` is the underlying primitive numeric type.
  //
  // Quantities support most basic arithmetic operators, intelligently handling units, and
  // automatically casting the underlying type in the same way that the compiler would.
  //
  // To convert a primitive number to a Quantity, multiply it by unit<Quantity<N, U>>().
  // To convert a Quantity to a primitive number, divide it by unit<Quantity<N, U>>().
  // To convert a Quantity of one unit to another unit, multiply or divide by a UnitRatio.
  //
  // The Quantity class is not well-suited to hardcore physics as it does not allow multiplying
  // one quantity by another.  For example, multiplying meters by meters won't get you square
  // meters; it will get you a compiler error.  It would be interesting to see if template
  // metaprogramming could properly deal with such things but this isn't needed for the present
  // use case.
  //
  // Sample usage:
  //
  //   class SecondsLabel;
  //   typedef Quantity<double, SecondsLabel> Seconds;
  //   constexpr Seconds SECONDS = unit<Seconds>();
  //
  //   class MinutesLabel;
  //   typedef Quantity<double, MinutesLabel> Minutes;
  //   constexpr Minutes MINUTES = unit<Minutes>();
  //
  //   constexpr UnitRatio<double, SecondsLabel, MinutesLabel> SECONDS_PER_MINUTE =
  //       60 * SECONDS / MINUTES;
  //
  //   void waitFor(Seconds seconds) {
  //     sleep(seconds / SECONDS);
  //   }
  //   void waitFor(Minutes minutes) {
  //     waitFor(minutes * SECONDS_PER_MINUTE);
  //   }
  //
  //   void waitThreeMinutes() {
  //     waitFor(3 * MINUTES);
  //   }

240
  static_assert(isIntegralOrBounded<Number>(),
241
      "Underlying type for Quantity must be integer.");
242

243
public:
244
  inline constexpr Quantity() = default;
245

246 247
  inline constexpr Quantity(MaxValue_): value(maxValue) {}
  inline constexpr Quantity(MinValue_): value(minValue) {}
248
  // Allow initialization from maxValue and minValue.
249 250 251
  // TODO(msvc): decltype(maxValue) and decltype(minValue) deduce unknown-type for these function
  // parameters, causing the compiler to complain of a duplicate constructor definition, so we
  // specify MaxValue_ and MinValue_ types explicitly.
252

253
  inline constexpr Quantity(Number value, decltype(unsafe)): value(value) {}
254 255 256 257 258 259 260 261
  // This constructor was intended to be private, but GCC complains about it being private in a
  // bunch of places that don't appear to even call it, so I made it public.  Oh well.

  template <typename OtherNumber>
  inline constexpr Quantity(const Quantity<OtherNumber, Unit>& other)
      : value(other.value) {}

  template <typename OtherNumber>
262 263 264 265 266 267 268
  inline Quantity& operator=(const Quantity<OtherNumber, Unit>& other) {
    value = other.value;
    return *this;
  }

  template <typename OtherNumber>
  inline constexpr Quantity<decltype(Number() + OtherNumber()), Unit>
269
      operator+(const Quantity<OtherNumber, Unit>& other) const {
270
    return Quantity<decltype(Number() + OtherNumber()), Unit>(value + other.value, unsafe);
271 272
  }
  template <typename OtherNumber>
273
  inline constexpr Quantity<decltype(Number() - OtherNumber()), Unit>
274
      operator-(const Quantity<OtherNumber, Unit>& other) const {
275
    return Quantity<decltype(Number() - OtherNumber()), Unit>(value - other.value, unsafe);
276
  }
277
  template <typename OtherNumber, typename = EnableIf<isIntegralOrBounded<OtherNumber>()>>
278
  inline constexpr Quantity<decltype(Number() * OtherNumber()), Unit>
279
      operator*(OtherNumber other) const {
280
    return Quantity<decltype(Number() * other), Unit>(value * other, unsafe);
281
  }
282
  template <typename OtherNumber, typename = EnableIf<isIntegralOrBounded<OtherNumber>()>>
283
  inline constexpr Quantity<decltype(Number() / OtherNumber()), Unit>
284
      operator/(OtherNumber other) const {
285
    return Quantity<decltype(Number() / other), Unit>(value / other, unsafe);
286 287
  }
  template <typename OtherNumber>
288
  inline constexpr decltype(Number() / OtherNumber())
289 290 291 292
      operator/(const Quantity<OtherNumber, Unit>& other) const {
    return value / other.value;
  }
  template <typename OtherNumber>
293
  inline constexpr Quantity<decltype(Number() % OtherNumber()), Unit>
294
      operator%(const Quantity<OtherNumber, Unit>& other) const {
295
    return Quantity<decltype(Number() % OtherNumber()), Unit>(value % other.value, unsafe);
296 297 298
  }

  template <typename OtherNumber, typename OtherUnit>
299
  inline constexpr Quantity<decltype(Number() * OtherNumber()), OtherUnit>
300
      operator*(UnitRatio<OtherNumber, OtherUnit, Unit> ratio) const {
301 302
    return Quantity<decltype(Number() * OtherNumber()), OtherUnit>(
        value * ratio.unit1PerUnit2, unsafe);
303 304
  }
  template <typename OtherNumber, typename OtherUnit>
305
  inline constexpr Quantity<decltype(Number() / OtherNumber()), OtherUnit>
306
      operator/(UnitRatio<OtherNumber, Unit, OtherUnit> ratio) const {
307 308
    return Quantity<decltype(Number() / OtherNumber()), OtherUnit>(
        value / ratio.unit1PerUnit2, unsafe);
309 310
  }
  template <typename OtherNumber, typename OtherUnit>
311
  inline constexpr Quantity<decltype(Number() % OtherNumber()), Unit>
312
      operator%(UnitRatio<OtherNumber, Unit, OtherUnit> ratio) const {
313 314
    return Quantity<decltype(Number() % OtherNumber()), Unit>(
        value % ratio.unit1PerUnit2, unsafe);
315 316
  }
  template <typename OtherNumber, typename OtherUnit>
317
  inline constexpr UnitRatio<decltype(Number() / OtherNumber()), Unit, OtherUnit>
318
      operator/(Quantity<OtherNumber, OtherUnit> other) const {
319 320
    return UnitRatio<decltype(Number() / OtherNumber()), Unit, OtherUnit>(
        value / other.value, unsafe);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
  }

  template <typename OtherNumber>
  inline constexpr bool operator==(const Quantity<OtherNumber, Unit>& other) const {
    return value == other.value;
  }
  template <typename OtherNumber>
  inline constexpr bool operator!=(const Quantity<OtherNumber, Unit>& other) const {
    return value != other.value;
  }
  template <typename OtherNumber>
  inline constexpr bool operator<=(const Quantity<OtherNumber, Unit>& other) const {
    return value <= other.value;
  }
  template <typename OtherNumber>
  inline constexpr bool operator>=(const Quantity<OtherNumber, Unit>& other) const {
    return value >= other.value;
  }
  template <typename OtherNumber>
  inline constexpr bool operator<(const Quantity<OtherNumber, Unit>& other) const {
    return value < other.value;
  }
  template <typename OtherNumber>
  inline constexpr bool operator>(const Quantity<OtherNumber, Unit>& other) const {
    return value > other.value;
  }

  template <typename OtherNumber>
  inline Quantity& operator+=(const Quantity<OtherNumber, Unit>& other) {
    value += other.value;
    return *this;
  }
  template <typename OtherNumber>
  inline Quantity& operator-=(const Quantity<OtherNumber, Unit>& other) {
    value -= other.value;
    return *this;
  }
  template <typename OtherNumber>
  inline Quantity& operator*=(OtherNumber other) {
    value *= other;
    return *this;
  }
  template <typename OtherNumber>
  inline Quantity& operator/=(OtherNumber other) {
    value /= other.value;
    return *this;
  }

private:
  Number value;

  template <typename OtherNumber, typename OtherUnit>
  friend class Quantity;

  template <typename Number1, typename Number2, typename Unit2>
  friend inline constexpr auto operator*(Number1 a, Quantity<Number2, Unit2> b)
377
      -> Quantity<decltype(Number1() * Number2()), Unit2>;
378 379
};

380 381 382 383 384 385 386 387 388 389
template <typename T> struct Unit_ {
  static inline constexpr T get() { return T(1); }
};
template <typename T, typename U>
struct Unit_<Quantity<T, U>> {
  static inline constexpr Quantity<decltype(Unit_<T>::get()), U> get() {
    return Quantity<decltype(Unit_<T>::get()), U>(Unit_<T>::get(), unsafe);
  }
};

390
template <typename T>
391
inline constexpr auto unit() -> decltype(Unit_<T>::get()) { return Unit_<T>::get(); }
392 393 394 395 396
// unit<Quantity<T, U>>() returns a Quantity of value 1.  It also, intentionally, works on basic
// numeric types.

template <typename Number1, typename Number2, typename Unit>
inline constexpr auto operator*(Number1 a, Quantity<Number2, Unit> b)
397 398
    -> Quantity<decltype(Number1() * Number2()), Unit> {
  return Quantity<decltype(Number1() * Number2()), Unit>(a * b.value, unsafe);
399 400 401 402 403 404 405 406 407
}

template <typename Number1, typename Number2, typename Unit, typename Unit2>
inline constexpr auto operator*(UnitRatio<Number1, Unit2, Unit> ratio,
    Quantity<Number2, Unit> measure)
    -> decltype(measure * ratio) {
  return measure * ratio;
}

408 409 410 411 412 413
// =======================================================================================
// Absolute measures

template <typename T, typename Label>
class Absolute {
  // Wraps some other value -- typically a Quantity -- but represents a value measured based on
414
  // some absolute origin.  For example, if `Duration` is a type representing a time duration,
415 416 417 418 419 420 421 422 423 424 425
  // Absolute<Duration, UnixEpoch> might be a calendar date.
  //
  // Since Absolute represents measurements relative to some arbitrary origin, the only sensible
  // arithmetic to perform on them is addition and subtraction.

  // TODO(someday):  Do the same automatic expansion of integer width that Quantity does?  Doesn't
  //   matter for our time use case, where we always use 64-bit anyway.  Note that fixing this
  //   would implicitly allow things like multiplying an Absolute by a UnitRatio to change its
  //   units, which is actually totally logical and kind of neat.

public:
426 427 428 429 430 431 432
  inline constexpr Absolute(MaxValue_): value(maxValue) {}
  inline constexpr Absolute(MinValue_): value(minValue) {}
  // Allow initialization from maxValue and minValue.
  // TODO(msvc): decltype(maxValue) and decltype(minValue) deduce unknown-type for these function
  // parameters, causing the compiler to complain of a duplicate constructor definition, so we
  // specify MaxValue_ and MinValue_ types explicitly.

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
  inline constexpr Absolute operator+(const T& other) const { return Absolute(value + other); }
  inline constexpr Absolute operator-(const T& other) const { return Absolute(value - other); }
  inline constexpr T operator-(const Absolute& other) const { return value - other.value; }

  inline Absolute& operator+=(const T& other) { value += other; return *this; }
  inline Absolute& operator-=(const T& other) { value -= other; return *this; }

  inline constexpr bool operator==(const Absolute& other) const { return value == other.value; }
  inline constexpr bool operator!=(const Absolute& other) const { return value != other.value; }
  inline constexpr bool operator<=(const Absolute& other) const { return value <= other.value; }
  inline constexpr bool operator>=(const Absolute& other) const { return value >= other.value; }
  inline constexpr bool operator< (const Absolute& other) const { return value <  other.value; }
  inline constexpr bool operator> (const Absolute& other) const { return value >  other.value; }

private:
  T value;

  explicit constexpr Absolute(T value): value(value) {}

  template <typename U>
  friend inline constexpr U origin();
};

template <typename T, typename Label>
inline constexpr Absolute<T, Label> operator+(const T& a, const Absolute<T, Label>& b) {
  return b + a;
}

template <typename T> struct UnitOf_ { typedef T Type; };
template <typename T, typename Label> struct UnitOf_<Absolute<T, Label>> { typedef T Type; };
template <typename T>
using UnitOf = typename UnitOf_<T>::Type;
// UnitOf<Absolute<T, U>> is T.  UnitOf<AnythingElse> is AnythingElse.

template <typename T>
inline constexpr T origin() { return T(0 * unit<UnitOf<T>>()); }
// origin<Absolute<T, U>>() returns an Absolute of value 0.  It also, intentionally, works on basic
// numeric types.

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
// =======================================================================================
// Overflow avoidance

template <uint64_t n, uint accum = 0>
struct BitCount_ {
  static constexpr uint value = BitCount_<(n >> 1), accum + 1>::value;
};
template <uint accum>
struct BitCount_<0, accum> {
  static constexpr uint value = accum;
};

template <uint64_t n>
inline constexpr uint bitCount() { return BitCount_<n>::value; }
// Number of bits required to represent the number `n`.

template <uint bitCountBitCount> struct AtLeastUInt_ {
  static_assert(bitCountBitCount < 7, "don't know how to represent integers over 64 bits");
};
template <> struct AtLeastUInt_<0> { typedef uint8_t Type; };
template <> struct AtLeastUInt_<1> { typedef uint8_t Type; };
template <> struct AtLeastUInt_<2> { typedef uint8_t Type; };
template <> struct AtLeastUInt_<3> { typedef uint8_t Type; };
template <> struct AtLeastUInt_<4> { typedef uint16_t Type; };
template <> struct AtLeastUInt_<5> { typedef uint32_t Type; };
template <> struct AtLeastUInt_<6> { typedef uint64_t Type; };

template <uint bits>
using AtLeastUInt = typename AtLeastUInt_<bitCount<max(bits, 1) - 1>()>::Type;
// AtLeastUInt<n> is an unsigned integer of at least n bits. E.g. AtLeastUInt<12> is uint16_t.

// -------------------------------------------------------------------

template <uint value>
506
class BoundedConst {
507 508 509
  // A constant integer value on which we can do bit size analysis.

public:
510
  BoundedConst() = default;
511

512 513 514 515
  inline constexpr uint unwrap() const { return value; }

#define OP(op, check) \
  template <uint other> \
516 517 518 519
  inline constexpr BoundedConst<(value op other)> \
      operator op(BoundedConst<other>) const { \
    static_assert(check, "overflow in BoundedConst arithmetic"); \
    return BoundedConst<(value op other)>(); \
520 521 522
  }
#define COMPARE_OP(op) \
  template <uint other> \
523
  inline constexpr bool operator op(BoundedConst<other>) const { \
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    return value op other; \
  }

  OP(+, value + other >= value)
  OP(-, value - other <= value)
  OP(*, value * other / other == value)
  OP(/, true)   // div by zero already errors out; no other division ever overflows
  OP(%, true)   // mod by zero already errors out; no other modulus ever overflows
  OP(<<, value << other >= value)
  OP(>>, true)  // right shift can't overflow
  OP(&, true)   // bitwise ops can't overflow
  OP(|, true)   // bitwise ops can't overflow

  COMPARE_OP(==)
  COMPARE_OP(!=)
  COMPARE_OP(< )
  COMPARE_OP(> )
  COMPARE_OP(<=)
  COMPARE_OP(>=)
#undef OP
#undef COMPARE_OP
};

template <uint64_t m, typename T>
548 549
struct Unit_<Bounded<m, T>> {
  static inline constexpr BoundedConst<1> get() { return BoundedConst<1>(); }
550 551 552
};

template <uint value>
553 554
struct Unit_<BoundedConst<value>> {
  static inline constexpr BoundedConst<1> get() { return BoundedConst<1>(); }
555 556 557
};

template <uint value>
558 559
inline constexpr BoundedConst<value> bounded() {
  return BoundedConst<value>();
560 561 562
}

template <uint64_t a, uint64_t b>
563
static constexpr uint64_t boundedAdd() {
564 565 566 567
  static_assert(a + b >= a, "possible overflow detected");
  return a + b;
}
template <uint64_t a, uint64_t b>
568
static constexpr uint64_t boundedSub() {
569 570 571 572
  static_assert(a - b <= a, "possible underflow detected");
  return a - b;
}
template <uint64_t a, uint64_t b>
573
static constexpr uint64_t boundedMul() {
574 575 576 577
  static_assert(a * b / b == a, "possible overflow detected");
  return a * b;
}
template <uint64_t a, uint64_t b>
578
static constexpr uint64_t boundedLShift() {
579 580 581 582
  static_assert(a << b >= a, "possible overflow detected");
  return a << b;
}

583
template <uint a, uint b>
584 585
inline constexpr BoundedConst<kj::min(a, b)> min(BoundedConst<a>, BoundedConst<b>) {
  return bounded<kj::min(a, b)>();
586 587
}
template <uint a, uint b>
588 589
inline constexpr BoundedConst<kj::max(a, b)> max(BoundedConst<a>, BoundedConst<b>) {
  return bounded<kj::max(a, b)>();
590 591 592 593
}
// We need to override min() and max() between constants because the ternary operator in the
// default implementation would complain.

594 595 596
// -------------------------------------------------------------------

template <uint64_t maxN, typename T>
597
class Bounded {
598 599 600
public:
  static_assert(maxN <= T(kj::maxValue), "possible overflow detected");

601
  Bounded() = default;
602

603
  Bounded(const Bounded& other) = default;
604
  template <typename OtherInt, typename = EnableIf<isIntegral<OtherInt>()>>
605
  inline constexpr Bounded(OtherInt value): value(value) {
606 607 608
    static_assert(OtherInt(maxValue) <= maxN, "possible overflow detected");
  }
  template <uint64_t otherMax, typename OtherT>
609
  inline constexpr Bounded(const Bounded<otherMax, OtherT>& other)
610 611 612 613
      : value(other.value) {
    static_assert(otherMax <= maxN, "possible overflow detected");
  }
  template <uint otherValue>
614
  inline constexpr Bounded(BoundedConst<otherValue>)
615 616 617 618
      : value(otherValue) {
    static_assert(otherValue <= maxN, "overflow detected");
  }

619
  Bounded& operator=(const Bounded& other) = default;
620
  template <typename OtherInt, typename = EnableIf<isIntegral<OtherInt>()>>
621
  Bounded& operator=(OtherInt other) {
622 623 624 625 626
    static_assert(OtherInt(maxValue) <= maxN, "possible overflow detected");
    value = other;
    return *this;
  }
  template <uint64_t otherMax, typename OtherT>
627
  inline Bounded& operator=(const Bounded<otherMax, OtherT>& other) {
628 629 630 631 632
    static_assert(otherMax <= maxN, "possible overflow detected");
    value = other.value;
    return *this;
  }
  template <uint otherValue>
633
  inline Bounded& operator=(BoundedConst<otherValue>) {
634 635 636 637 638 639 640 641 642
    static_assert(otherValue <= maxN, "overflow detected");
    value = otherValue;
    return *this;
  }

  inline constexpr T unwrap() const { return value; }

#define OP(op, newMax) \
  template <uint64_t otherMax, typename otherT> \
643 644 645
  inline constexpr Bounded<newMax, decltype(T() op otherT())> \
      operator op(const Bounded<otherMax, otherT>& other) const { \
    return Bounded<newMax, decltype(T() op otherT())>(value op other.value, unsafe); \
646 647 648
  }
#define COMPARE_OP(op) \
  template <uint64_t otherMax, typename OtherT> \
649
  inline constexpr bool operator op(const Bounded<otherMax, OtherT>& other) const { \
650 651 652
    return value op other.value; \
  }

653 654
  OP(+, (boundedAdd<maxN, otherMax>()))
  OP(*, (boundedMul<maxN, otherMax>()))
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
  OP(/, maxN)
  OP(%, otherMax - 1)

  // operator- is intentionally omitted because we mostly use this with unsigned types, and
  // subtraction requires proof that subtrahend is not greater than the minuend.

  COMPARE_OP(==)
  COMPARE_OP(!=)
  COMPARE_OP(< )
  COMPARE_OP(> )
  COMPARE_OP(<=)
  COMPARE_OP(>=)

#undef OP
#undef COMPARE_OP

  template <uint64_t newMax, typename ErrorFunc>
672
  inline Bounded<newMax, T> assertMax(ErrorFunc&& func) const {
673
    // Assert that the number is no more than `newMax`. Otherwise, call `func`.
674
    static_assert(newMax < maxN, "this bounded size assertion is redundant");
675
    if (KJ_UNLIKELY(value > newMax)) func();
676
    return Bounded<newMax, T>(value, unsafe);
677 678 679
  }

  template <uint64_t otherMax, typename OtherT, typename ErrorFunc>
680 681
  inline Bounded<maxN, decltype(T() - OtherT())> subtractChecked(
      const Bounded<otherMax, OtherT>& other, ErrorFunc&& func) const {
682 683
    // Subtract a number, calling func() if the result would underflow.
    if (KJ_UNLIKELY(value < other.value)) func();
684
    return Bounded<maxN, decltype(T() - OtherT())>(value - other.value, unsafe);
685 686 687
  }

  template <uint otherValue, typename ErrorFunc>
688 689
  inline Bounded<maxN - otherValue, T> subtractChecked(
      BoundedConst<otherValue>, ErrorFunc&& func) const {
690 691 692
    // Subtract a number, calling func() if the result would underflow.
    static_assert(otherValue <= maxN, "underflow detected");
    if (KJ_UNLIKELY(value < otherValue)) func();
693
    return Bounded<maxN - otherValue, T>(value - otherValue, unsafe);
694 695
  }

696
  template <uint64_t otherMax, typename OtherT>
697 698
  inline Maybe<Bounded<maxN, decltype(T() - OtherT())>> trySubtract(
      const Bounded<otherMax, OtherT>& other) const {
699 700 701 702
    // Subtract a number, calling func() if the result would underflow.
    if (value < other.value) {
      return nullptr;
    } else {
703
      return Bounded<maxN, decltype(T() - OtherT())>(value - other.value, unsafe);
704 705 706 707
    }
  }

  template <uint otherValue>
708
  inline Maybe<Bounded<maxN - otherValue, T>> trySubtract(BoundedConst<otherValue>) const {
709 710 711 712
    // Subtract a number, calling func() if the result would underflow.
    if (value < otherValue) {
      return nullptr;
    } else {
713
      return Bounded<maxN - otherValue, T>(value - otherValue, unsafe);
714 715 716
    }
  }

717
  inline constexpr Bounded(T value, decltype(unsafe)): value(value) {}
718
  template <uint64_t otherMax, typename OtherT>
719
  inline constexpr Bounded(Bounded<otherMax, OtherT> value, decltype(unsafe))
720 721 722 723 724 725 726 727 728
      : value(value.value) {}
  // Mainly for internal use.
  //
  // Only use these as a last resort, with ample commentary on why you think it's safe.

private:
  T value;

  template <uint64_t, typename>
729
  friend class Bounded;
730 731 732
};

template <typename Number>
733 734
inline constexpr Bounded<Number(kj::maxValue), Number> bounded(Number value) {
  return Bounded<Number(kj::maxValue), Number>(value, unsafe);
735 736
}

737 738
inline constexpr Bounded<1, uint8_t> bounded(bool value) {
  return Bounded<1, uint8_t>(value, unsafe);
739 740 741
}

template <uint bits, typename Number>
742 743
inline constexpr Bounded<maxValueForBits<bits>(), Number> assumeBits(Number value) {
  return Bounded<maxValueForBits<bits>(), Number>(value, unsafe);
744 745 746
}

template <uint bits, uint64_t maxN, typename T>
747 748
inline constexpr Bounded<maxValueForBits<bits>(), T> assumeBits(Bounded<maxN, T> value) {
  return Bounded<maxValueForBits<bits>(), T>(value, unsafe);
749 750 751 752 753 754 755 756 757
}

template <uint bits, typename Number, typename Unit>
inline constexpr auto assumeBits(Quantity<Number, Unit> value)
    -> Quantity<decltype(assumeBits<bits>(value / unit<Quantity<Number, Unit>>())), Unit> {
  return Quantity<decltype(assumeBits<bits>(value / unit<Quantity<Number, Unit>>())), Unit>(
      assumeBits<bits>(value / unit<Quantity<Number, Unit>>()), unsafe);
}

758
template <uint64_t maxN, typename Number>
759 760
inline constexpr Bounded<maxN, Number> assumeMax(Number value) {
  return Bounded<maxN, Number>(value, unsafe);
761 762 763
}

template <uint64_t newMaxN, uint64_t maxN, typename T>
764 765
inline constexpr Bounded<newMaxN, T> assumeMax(Bounded<maxN, T> value) {
  return Bounded<newMaxN, T>(value, unsafe);
766 767 768 769 770 771 772 773 774 775
}

template <uint64_t maxN, typename Number, typename Unit>
inline constexpr auto assumeMax(Quantity<Number, Unit> value)
    -> Quantity<decltype(assumeMax<maxN>(value / unit<Quantity<Number, Unit>>())), Unit> {
  return Quantity<decltype(assumeMax<maxN>(value / unit<Quantity<Number, Unit>>())), Unit>(
      assumeMax<maxN>(value / unit<Quantity<Number, Unit>>()), unsafe);
}

template <uint maxN, typename Number>
776
inline constexpr Bounded<maxN, Number> assumeMax(BoundedConst<maxN>, Number value) {
777 778 779 780
  return assumeMax<maxN>(value);
}

template <uint newMaxN, uint64_t maxN, typename T>
781
inline constexpr Bounded<newMaxN, T> assumeMax(BoundedConst<maxN>, Bounded<maxN, T> value) {
782 783 784 785
  return assumeMax<maxN>(value);
}

template <uint maxN, typename Number, typename Unit>
786
inline constexpr auto assumeMax(Quantity<BoundedConst<maxN>, Unit>, Quantity<Number, Unit> value)
787 788 789 790
    -> decltype(assumeMax<maxN>(value)) {
  return assumeMax<maxN>(value);
}

791
template <uint64_t newMax, uint64_t maxN, typename T, typename ErrorFunc>
792
inline Bounded<newMax, T> assertMax(Bounded<maxN, T> value, ErrorFunc&& errorFunc) {
793
  // Assert that the bounded value is less than or equal to the given maximum, calling errorFunc()
794
  // if not.
795
  static_assert(newMax < maxN, "this bounded size assertion is redundant");
796 797 798 799
  return value.template assertMax<newMax>(kj::fwd<ErrorFunc>(errorFunc));
}

template <uint64_t newMax, uint64_t maxN, typename T, typename Unit, typename ErrorFunc>
800
inline Quantity<Bounded<newMax, T>, Unit> assertMax(
801 802
    Quantity<Bounded<maxN, T>, Unit> value, ErrorFunc&& errorFunc) {
  // Assert that the bounded value is less than or equal to the given maximum, calling errorFunc()
803
  // if not.
804
  static_assert(newMax < maxN, "this bounded size assertion is redundant");
805 806 807 808
  return (value / unit<decltype(value)>()).template assertMax<newMax>(
      kj::fwd<ErrorFunc>(errorFunc)) * unit<decltype(value)>();
}

809
template <uint newMax, uint64_t maxN, typename T, typename ErrorFunc>
810
inline Bounded<newMax, T> assertMax(
811
    BoundedConst<newMax>, Bounded<maxN, T> value, ErrorFunc&& errorFunc) {
812 813 814 815
  return assertMax<newMax>(value, kj::mv(errorFunc));
}

template <uint newMax, uint64_t maxN, typename T, typename Unit, typename ErrorFunc>
816
inline Quantity<Bounded<newMax, T>, Unit> assertMax(
817 818
    Quantity<BoundedConst<newMax>, Unit>,
    Quantity<Bounded<maxN, T>, Unit> value, ErrorFunc&& errorFunc) {
819 820 821
  return assertMax<newMax>(value, kj::mv(errorFunc));
}

822
template <uint64_t newBits, uint64_t maxN, typename T, typename ErrorFunc = ThrowOverflow>
823
inline Bounded<maxValueForBits<newBits>(), T> assertMaxBits(
824 825
    Bounded<maxN, T> value, ErrorFunc&& errorFunc = ErrorFunc()) {
  // Assert that the bounded value requires no more than the given number of bits, calling
826 827 828 829 830 831
  // errorFunc() if not.
  return assertMax<maxValueForBits<newBits>()>(value, kj::fwd<ErrorFunc>(errorFunc));
}

template <uint64_t newBits, uint64_t maxN, typename T, typename Unit,
          typename ErrorFunc = ThrowOverflow>
832
inline Quantity<Bounded<maxValueForBits<newBits>(), T>, Unit> assertMaxBits(
833 834
    Quantity<Bounded<maxN, T>, Unit> value, ErrorFunc&& errorFunc = ErrorFunc()) {
  // Assert that the bounded value requires no more than the given number of bits, calling
835 836 837 838 839
  // errorFunc() if not.
  return assertMax<maxValueForBits<newBits>()>(value, kj::fwd<ErrorFunc>(errorFunc));
}

template <typename newT, uint64_t maxN, typename T>
840
inline constexpr Bounded<maxN, newT> upgradeBound(Bounded<maxN, T> value) {
841 842 843 844
  return value;
}

template <typename newT, uint64_t maxN, typename T, typename Unit>
845 846
inline constexpr Quantity<Bounded<maxN, newT>, Unit> upgradeBound(
    Quantity<Bounded<maxN, T>, Unit> value) {
847 848 849 850
  return value;
}

template <uint64_t maxN, typename T, typename Other, typename ErrorFunc>
851
inline auto subtractChecked(Bounded<maxN, T> value, Other other, ErrorFunc&& errorFunc)
852 853 854 855 856 857 858 859 860 861 862 863 864
    -> decltype(value.subtractChecked(other, kj::fwd<ErrorFunc>(errorFunc))) {
  return value.subtractChecked(other, kj::fwd<ErrorFunc>(errorFunc));
}

template <typename T, typename U, typename Unit, typename ErrorFunc>
inline auto subtractChecked(Quantity<T, Unit> value, Quantity<U, Unit> other, ErrorFunc&& errorFunc)
    -> Quantity<decltype(subtractChecked(T(), U(), kj::fwd<ErrorFunc>(errorFunc))), Unit> {
  return subtractChecked(value / unit<Quantity<T, Unit>>(),
                         other / unit<Quantity<U, Unit>>(),
                         kj::fwd<ErrorFunc>(errorFunc))
      * unit<Quantity<T, Unit>>();
}

865
template <uint64_t maxN, typename T, typename Other>
866
inline auto trySubtract(Bounded<maxN, T> value, Other other)
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    -> decltype(value.trySubtract(other)) {
  return value.trySubtract(other);
}

template <typename T, typename U, typename Unit>
inline auto trySubtract(Quantity<T, Unit> value, Quantity<U, Unit> other)
    -> Maybe<Quantity<decltype(subtractChecked(T(), U(), int())), Unit>> {
  return trySubtract(value / unit<Quantity<T, Unit>>(),
                     other / unit<Quantity<U, Unit>>())
      .map([](decltype(subtractChecked(T(), U(), int())) x) {
    return x * unit<Quantity<T, Unit>>();
  });
}

template <uint64_t aN, uint64_t bN, typename A, typename B>
882 883
inline constexpr Bounded<kj::min(aN, bN), WiderType<A, B>>
min(Bounded<aN, A> a, Bounded<bN, B> b) {
Kenton Varda's avatar
Kenton Varda committed
884
  return Bounded<kj::min(aN, bN), WiderType<A, B>>(kj::min(a.unwrap(), b.unwrap()), unsafe);
885 886
}
template <uint64_t aN, uint64_t bN, typename A, typename B>
887 888
inline constexpr Bounded<kj::max(aN, bN), WiderType<A, B>>
max(Bounded<aN, A> a, Bounded<bN, B> b) {
Kenton Varda's avatar
Kenton Varda committed
889
  return Bounded<kj::max(aN, bN), WiderType<A, B>>(kj::max(a.unwrap(), b.unwrap()), unsafe);
890 891 892 893 894 895
}
// We need to override min() and max() because:
// 1) WiderType<> might not choose the correct bounds.
// 2) One of the two sides of the ternary operator in the default implementation would fail to
//    typecheck even though it is OK in practice.

896
// -------------------------------------------------------------------
897
// Operators between Bounded and BoundedConst
898 899 900

#define OP(op, newMax) \
template <uint64_t maxN, uint cvalue, typename T> \
901 902 903
inline constexpr Bounded<(newMax), decltype(T() op uint())> operator op( \
    Bounded<maxN, T> value, BoundedConst<cvalue>) { \
  return Bounded<(newMax), decltype(T() op uint())>(value.unwrap() op cvalue, unsafe); \
904 905 906 907
}

#define REVERSE_OP(op, newMax) \
template <uint64_t maxN, uint cvalue, typename T> \
908 909 910
inline constexpr Bounded<(newMax), decltype(uint() op T())> operator op( \
    BoundedConst<cvalue>, Bounded<maxN, T> value) { \
  return Bounded<(newMax), decltype(uint() op T())>(cvalue op value.unwrap(), unsafe); \
911 912 913 914
}

#define COMPARE_OP(op) \
template <uint64_t maxN, uint cvalue, typename T> \
915
inline constexpr bool operator op(Bounded<maxN, T> value, BoundedConst<cvalue>) { \
916 917 918
  return value.unwrap() op cvalue; \
} \
template <uint64_t maxN, uint cvalue, typename T> \
919
inline constexpr bool operator op(BoundedConst<cvalue>, Bounded<maxN, T> value) { \
920 921 922
  return cvalue op value.unwrap(); \
}

923 924
OP(+, (boundedAdd<maxN, cvalue>()))
REVERSE_OP(+, (boundedAdd<maxN, cvalue>()))
925

926 927
OP(*, (boundedMul<maxN, cvalue>()))
REVERSE_OP(*, (boundedAdd<maxN, cvalue>()))
928 929 930 931 932 933 934

OP(/, maxN / cvalue)
REVERSE_OP(/, cvalue)  // denominator could be 1

OP(%, cvalue - 1)
REVERSE_OP(%, maxN - 1)

935 936
OP(<<, (boundedLShift<maxN, cvalue>()))
REVERSE_OP(<<, (boundedLShift<cvalue, maxN>()))
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958

OP(>>, maxN >> cvalue)
REVERSE_OP(>>, cvalue >> maxN)

OP(&, maxValueForBits<bitCount<maxN>()>() & cvalue)
REVERSE_OP(&, maxValueForBits<bitCount<maxN>()>() & cvalue)

OP(|, maxN | cvalue)
REVERSE_OP(|, maxN | cvalue)

COMPARE_OP(==)
COMPARE_OP(!=)
COMPARE_OP(< )
COMPARE_OP(> )
COMPARE_OP(<=)
COMPARE_OP(>=)

#undef OP
#undef REVERSE_OP
#undef COMPARE_OP

template <uint64_t maxN, uint cvalue, typename T>
959 960
inline constexpr Bounded<cvalue, decltype(uint() - T())>
    operator-(BoundedConst<cvalue>, Bounded<maxN, T> value) {
961 962 963 964 965 966 967
  // We allow subtraction of a variable from a constant only if the constant is greater than or
  // equal to the maximum possible value of the variable. Since the variable could be zero, the
  // result can be as large as the constant.
  //
  // We do not allow subtraction of a constant from a variable because there's never a guarantee it
  // won't underflow (unless the constant is zero, which is silly).
  static_assert(cvalue >= maxN, "possible underflow detected");
968
  return Bounded<cvalue, decltype(uint() - T())>(cvalue - value.unwrap(), unsafe);
969 970
}

971
template <uint64_t aN, uint b, typename A>
972
inline constexpr Bounded<kj::min(aN, b), A> min(Bounded<aN, A> a, BoundedConst<b>) {
Kenton Varda's avatar
Kenton Varda committed
973
  return Bounded<kj::min(aN, b), A>(kj::min(b, a.unwrap()), unsafe);
974 975
}
template <uint64_t aN, uint b, typename A>
976
inline constexpr Bounded<kj::min(aN, b), A> min(BoundedConst<b>, Bounded<aN, A> a) {
Kenton Varda's avatar
Kenton Varda committed
977
  return Bounded<kj::min(aN, b), A>(kj::min(a.unwrap(), b), unsafe);
978 979
}
template <uint64_t aN, uint b, typename A>
980
inline constexpr Bounded<kj::max(aN, b), A> max(Bounded<aN, A> a, BoundedConst<b>) {
Kenton Varda's avatar
Kenton Varda committed
981
  return Bounded<kj::max(aN, b), A>(kj::max(b, a.unwrap()), unsafe);
982 983
}
template <uint64_t aN, uint b, typename A>
984
inline constexpr Bounded<kj::max(aN, b), A> max(BoundedConst<b>, Bounded<aN, A> a) {
Kenton Varda's avatar
Kenton Varda committed
985
  return Bounded<kj::max(aN, b), A>(kj::max(a.unwrap(), b), unsafe);
986
}
987 988
// We need to override min() between a Bounded and a constant since:
// 1) WiderType<> might choose BoundedConst over a 1-byte Bounded, which is wrong.
989 990 991
// 2) To clamp the bounds of the output type.
// 3) Same ternary operator typechecking issues.

992 993 994 995 996
// -------------------------------------------------------------------

template <uint64_t maxN, typename T>
class SafeUnwrapper {
public:
997
  inline explicit constexpr SafeUnwrapper(Bounded<maxN, T> value): value(value.unwrap()) {}
998 999

  template <typename U, typename = EnableIf<isIntegral<U>()>>
1000
  inline constexpr operator U() const {
1001 1002 1003 1004
    static_assert(maxN <= U(maxValue), "possible truncation detected");
    return value;
  }

1005
  inline constexpr operator bool() const {
1006 1007 1008 1009 1010 1011 1012 1013 1014
    static_assert(maxN <= 1, "possible truncation detected");
    return value;
  }

private:
  T value;
};

template <uint64_t maxN, typename T>
1015 1016
inline constexpr SafeUnwrapper<maxN, T> unbound(Bounded<maxN, T> bounded) {
  // Unwraps the bounded value, returning a value that can be implicitly cast to any integer type.
1017
  // If this implicit cast could truncate, a compile-time error will be raised.
1018
  return SafeUnwrapper<maxN, T>(bounded);
1019 1020 1021 1022 1023 1024
}

template <uint64_t value>
class SafeConstUnwrapper {
public:
  template <typename T, typename = EnableIf<isIntegral<T>()>>
1025
  inline constexpr operator T() const {
1026 1027 1028 1029
    static_assert(value <= T(maxValue), "this operation will truncate");
    return value;
  }

1030
  inline constexpr operator bool() const {
1031 1032 1033 1034 1035 1036
    static_assert(value <= 1, "this operation will truncate");
    return value;
  }
};

template <uint value>
1037
inline constexpr SafeConstUnwrapper<value> unbound(BoundedConst<value>) {
1038 1039 1040 1041
  return SafeConstUnwrapper<value>();
}

template <typename T, typename U>
1042 1043
inline constexpr T unboundAs(U value) {
  return unbound(value);
1044 1045 1046
}

template <uint64_t requestedMax, uint64_t maxN, typename T>
1047
inline constexpr T unboundMax(Bounded<maxN, T> value) {
1048 1049 1050 1051 1052 1053
  // Explicitly ungaurd expecting a value that is at most `maxN`.
  static_assert(maxN <= requestedMax, "possible overflow detected");
  return value.unwrap();
}

template <uint64_t requestedMax, uint value>
1054
inline constexpr uint unboundMax(BoundedConst<value>) {
1055 1056 1057 1058 1059 1060
  // Explicitly ungaurd expecting a value that is at most `maxN`.
  static_assert(value <= requestedMax, "overflow detected");
  return value;
}

template <uint bits, typename T>
1061 1062
inline constexpr auto unboundMaxBits(T value) ->
    decltype(unboundMax<maxValueForBits<bits>()>(value)) {
1063
  // Explicitly ungaurd expecting a value that fits into `bits` bits.
1064
  return unboundMax<maxValueForBits<bits>()>(value);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
}

#define OP(op) \
template <uint64_t maxN, typename T, typename U> \
inline constexpr auto operator op(T a, SafeUnwrapper<maxN, U> b) -> decltype(a op (T)b) { \
  return a op (AtLeastUInt<sizeof(T)*8>)b; \
} \
template <uint64_t maxN, typename T, typename U> \
inline constexpr auto operator op(SafeUnwrapper<maxN, U> b, T a) -> decltype((T)b op a) { \
  return (AtLeastUInt<sizeof(T)*8>)b op a; \
} \
template <uint64_t value, typename T> \
inline constexpr auto operator op(T a, SafeConstUnwrapper<value> b) -> decltype(a op (T)b) { \
  return a op (AtLeastUInt<sizeof(T)*8>)b; \
} \
template <uint64_t value, typename T> \
inline constexpr auto operator op(SafeConstUnwrapper<value> b, T a) -> decltype((T)b op a) { \
  return (AtLeastUInt<sizeof(T)*8>)b op a; \
}

OP(+)
OP(-)
OP(*)
OP(/)
OP(%)
OP(<<)
OP(>>)
OP(&)
OP(|)
OP(==)
OP(!=)
OP(<=)
OP(>=)
OP(<)
OP(>)

#undef OP

// -------------------------------------------------------------------

template <uint64_t maxN, typename T>
1106
class Range<Bounded<maxN, T>> {
1107
public:
1108 1109 1110 1111
  inline constexpr Range(Bounded<maxN, T> begin, Bounded<maxN, T> end)
      : inner(unbound(begin), unbound(end)) {}
  inline explicit constexpr Range(Bounded<maxN, T> end)
      : inner(unbound(end)) {}
1112 1113 1114 1115 1116 1117

  class Iterator {
  public:
    Iterator() = default;
    inline explicit Iterator(typename Range<T>::Iterator inner): inner(inner) {}

1118
    inline Bounded<maxN, T> operator* () const { return Bounded<maxN, T>(*inner, unsafe); }
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    inline Iterator& operator++() { ++inner; return *this; }

    inline bool operator==(const Iterator& other) const { return inner == other.inner; }
    inline bool operator!=(const Iterator& other) const { return inner != other.inner; }

  private:
    typename Range<T>::Iterator inner;
  };

  inline Iterator begin() const { return Iterator(inner.begin()); }
  inline Iterator end() const { return Iterator(inner.end()); }

private:
  Range<T> inner;
};

template <typename T, typename U>
class Range<Quantity<T, U>> {
public:
  inline constexpr Range(Quantity<T, U> begin, Quantity<T, U> end)
      : inner(begin / unit<Quantity<T, U>>(), end / unit<Quantity<T, U>>()) {}
  inline explicit constexpr Range(Quantity<T, U> end)
      : inner(end / unit<Quantity<T, U>>()) {}

  class Iterator {
  public:
    Iterator() = default;
    inline explicit Iterator(typename Range<T>::Iterator inner): inner(inner) {}

    inline Quantity<T, U> operator* () const { return *inner * unit<Quantity<T, U>>(); }
    inline Iterator& operator++() { ++inner; return *this; }

    inline bool operator==(const Iterator& other) const { return inner == other.inner; }
    inline bool operator!=(const Iterator& other) const { return inner != other.inner; }

  private:
    typename Range<T>::Iterator inner;
  };

  inline Iterator begin() const { return Iterator(inner.begin()); }
  inline Iterator end() const { return Iterator(inner.end()); }

private:
  Range<T> inner;
};

template <uint value>
1166 1167
inline constexpr Range<Bounded<value, uint>> zeroTo(BoundedConst<value> end) {
  return Range<Bounded<value, uint>>(end);
1168 1169 1170
}

template <uint value, typename Unit>
1171 1172 1173
inline constexpr Range<Quantity<Bounded<value, uint>, Unit>>
    zeroTo(Quantity<BoundedConst<value>, Unit> end) {
  return Range<Quantity<Bounded<value, uint>, Unit>>(end);
1174 1175
}

1176
}  // namespace kj