Chris@63: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@63: // Licensed under the MIT License: Chris@63: // Chris@63: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@63: // of this software and associated documentation files (the "Software"), to deal Chris@63: // in the Software without restriction, including without limitation the rights Chris@63: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@63: // copies of the Software, and to permit persons to whom the Software is Chris@63: // furnished to do so, subject to the following conditions: Chris@63: // Chris@63: // The above copyright notice and this permission notice shall be included in Chris@63: // all copies or substantial portions of the Software. Chris@63: // Chris@63: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@63: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@63: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@63: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@63: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@63: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@63: // THE SOFTWARE. Chris@63: Chris@63: // This file contains types which are intended to help detect incorrect usage at compile Chris@63: // time, but should then be optimized down to basic primitives (usually, integers) by the Chris@63: // compiler. Chris@63: Chris@63: #ifndef KJ_UNITS_H_ Chris@63: #define KJ_UNITS_H_ Chris@63: Chris@63: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@63: #pragma GCC system_header Chris@63: #endif Chris@63: Chris@63: #include "common.h" Chris@63: #include Chris@63: Chris@63: namespace kj { Chris@63: Chris@63: // ======================================================================================= Chris@63: // IDs Chris@63: Chris@63: template Chris@63: struct Id { Chris@63: // A type-safe numeric ID. `UnderlyingType` is the underlying integer representation. `Label` Chris@63: // distinguishes this Id from other Id types. Sample usage: Chris@63: // Chris@63: // class Foo; Chris@63: // typedef Id FooId; Chris@63: // Chris@63: // class Bar; Chris@63: // typedef Id BarId; Chris@63: // Chris@63: // You can now use the FooId and BarId types without any possibility of accidentally using a Chris@63: // FooId when you really wanted a BarId or vice-versa. Chris@63: Chris@63: UnderlyingType value; Chris@63: Chris@63: inline constexpr Id(): value(0) {} Chris@63: inline constexpr explicit Id(int value): value(value) {} Chris@63: Chris@63: inline constexpr bool operator==(const Id& other) const { return value == other.value; } Chris@63: inline constexpr bool operator!=(const Id& other) const { return value != other.value; } Chris@63: inline constexpr bool operator<=(const Id& other) const { return value <= other.value; } Chris@63: inline constexpr bool operator>=(const Id& other) const { return value >= other.value; } Chris@63: inline constexpr bool operator< (const Id& other) const { return value < other.value; } Chris@63: inline constexpr bool operator> (const Id& other) const { return value > other.value; } Chris@63: }; Chris@63: Chris@63: // ======================================================================================= Chris@63: // Quantity and UnitRatio -- implement unit analysis via the type system Chris@63: Chris@63: struct Unsafe_ {}; Chris@63: constexpr Unsafe_ unsafe = Unsafe_(); Chris@63: // Use as a parameter to constructors that are unsafe to indicate that you really do mean it. Chris@63: Chris@63: template Chris@63: class Bounded; Chris@63: template Chris@63: class BoundedConst; Chris@63: Chris@63: template constexpr bool isIntegral() { return false; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: template <> constexpr bool isIntegral() { return true; } Chris@63: Chris@63: template Chris@63: struct IsIntegralOrBounded_ { static constexpr bool value = isIntegral(); }; Chris@63: template Chris@63: struct IsIntegralOrBounded_> { static constexpr bool value = true; }; Chris@63: template Chris@63: struct IsIntegralOrBounded_> { static constexpr bool value = true; }; Chris@63: Chris@63: template Chris@63: inline constexpr bool isIntegralOrBounded() { return IsIntegralOrBounded_::value; } Chris@63: Chris@63: template Chris@63: class UnitRatio { Chris@63: // A multiplier used to convert Quantities of one unit to Quantities of another unit. See Chris@63: // Quantity, below. Chris@63: // Chris@63: // Construct this type by dividing one Quantity by another of a different unit. Use this type Chris@63: // by multiplying it by a Quantity, or dividing a Quantity by it. Chris@63: Chris@63: static_assert(isIntegralOrBounded(), Chris@63: "Underlying type for UnitRatio must be integer."); Chris@63: Chris@63: public: Chris@63: inline UnitRatio() {} Chris@63: Chris@63: constexpr UnitRatio(Number unit1PerUnit2, decltype(unsafe)): unit1PerUnit2(unit1PerUnit2) {} Chris@63: // This constructor was intended to be private, but GCC complains about it being private in a Chris@63: // bunch of places that don't appear to even call it, so I made it public. Oh well. Chris@63: Chris@63: template Chris@63: inline constexpr UnitRatio(const UnitRatio& other) Chris@63: : unit1PerUnit2(other.unit1PerUnit2) {} Chris@63: Chris@63: template Chris@63: inline constexpr UnitRatio Chris@63: operator+(UnitRatio other) const { Chris@63: return UnitRatio( Chris@63: unit1PerUnit2 + other.unit1PerUnit2, unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr UnitRatio Chris@63: operator-(UnitRatio other) const { Chris@63: return UnitRatio( Chris@63: unit1PerUnit2 - other.unit1PerUnit2, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr UnitRatio Chris@63: operator*(UnitRatio other) const { Chris@63: // U1 / U2 * U3 / U1 = U3 / U2 Chris@63: return UnitRatio( Chris@63: unit1PerUnit2 * other.unit1PerUnit2, unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr UnitRatio Chris@63: operator*(UnitRatio other) const { Chris@63: // U1 / U2 * U2 / U3 = U1 / U3 Chris@63: return UnitRatio( Chris@63: unit1PerUnit2 * other.unit1PerUnit2, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr UnitRatio Chris@63: operator/(UnitRatio other) const { Chris@63: // (U1 / U2) / (U1 / U3) = U3 / U2 Chris@63: return UnitRatio( Chris@63: unit1PerUnit2 / other.unit1PerUnit2, unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr UnitRatio Chris@63: operator/(UnitRatio other) const { Chris@63: // (U1 / U2) / (U3 / U2) = U1 / U3 Chris@63: return UnitRatio( Chris@63: unit1PerUnit2 / other.unit1PerUnit2, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline decltype(Number() / OtherNumber()) Chris@63: operator/(UnitRatio other) const { Chris@63: return unit1PerUnit2 / other.unit1PerUnit2; Chris@63: } Chris@63: Chris@63: inline bool operator==(UnitRatio other) const { return unit1PerUnit2 == other.unit1PerUnit2; } Chris@63: inline bool operator!=(UnitRatio other) const { return unit1PerUnit2 != other.unit1PerUnit2; } Chris@63: Chris@63: private: Chris@63: Number unit1PerUnit2; Chris@63: Chris@63: template Chris@63: friend class Quantity; Chris@63: template Chris@63: friend class UnitRatio; Chris@63: Chris@63: template Chris@63: friend inline constexpr UnitRatio Chris@63: operator*(N1, UnitRatio); Chris@63: }; Chris@63: Chris@63: template () && isIntegralOrBounded()>> Chris@63: inline constexpr UnitRatio Chris@63: operator*(N1 n, UnitRatio r) { Chris@63: return UnitRatio(n * r.unit1PerUnit2, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: class Quantity { Chris@63: // A type-safe numeric quantity, specified in terms of some unit. Two Quantities cannot be used Chris@63: // in arithmetic unless they use the same unit. The `Unit` type parameter is only used to prevent Chris@63: // accidental mixing of units; this type is never instantiated and can very well be incomplete. Chris@63: // `Number` is the underlying primitive numeric type. Chris@63: // Chris@63: // Quantities support most basic arithmetic operators, intelligently handling units, and Chris@63: // automatically casting the underlying type in the same way that the compiler would. Chris@63: // Chris@63: // To convert a primitive number to a Quantity, multiply it by unit>(). Chris@63: // To convert a Quantity to a primitive number, divide it by unit>(). Chris@63: // To convert a Quantity of one unit to another unit, multiply or divide by a UnitRatio. Chris@63: // Chris@63: // The Quantity class is not well-suited to hardcore physics as it does not allow multiplying Chris@63: // one quantity by another. For example, multiplying meters by meters won't get you square Chris@63: // meters; it will get you a compiler error. It would be interesting to see if template Chris@63: // metaprogramming could properly deal with such things but this isn't needed for the present Chris@63: // use case. Chris@63: // Chris@63: // Sample usage: Chris@63: // Chris@63: // class SecondsLabel; Chris@63: // typedef Quantity Seconds; Chris@63: // constexpr Seconds SECONDS = unit(); Chris@63: // Chris@63: // class MinutesLabel; Chris@63: // typedef Quantity Minutes; Chris@63: // constexpr Minutes MINUTES = unit(); Chris@63: // Chris@63: // constexpr UnitRatio SECONDS_PER_MINUTE = Chris@63: // 60 * SECONDS / MINUTES; Chris@63: // Chris@63: // void waitFor(Seconds seconds) { Chris@63: // sleep(seconds / SECONDS); Chris@63: // } Chris@63: // void waitFor(Minutes minutes) { Chris@63: // waitFor(minutes * SECONDS_PER_MINUTE); Chris@63: // } Chris@63: // Chris@63: // void waitThreeMinutes() { Chris@63: // waitFor(3 * MINUTES); Chris@63: // } Chris@63: Chris@63: static_assert(isIntegralOrBounded(), Chris@63: "Underlying type for Quantity must be integer."); Chris@63: Chris@63: public: Chris@63: inline constexpr Quantity() = default; Chris@63: Chris@63: inline constexpr Quantity(MaxValue_): value(maxValue) {} Chris@63: inline constexpr Quantity(MinValue_): value(minValue) {} Chris@63: // Allow initialization from maxValue and minValue. Chris@63: // TODO(msvc): decltype(maxValue) and decltype(minValue) deduce unknown-type for these function Chris@63: // parameters, causing the compiler to complain of a duplicate constructor definition, so we Chris@63: // specify MaxValue_ and MinValue_ types explicitly. Chris@63: Chris@63: inline constexpr Quantity(Number value, decltype(unsafe)): value(value) {} Chris@63: // This constructor was intended to be private, but GCC complains about it being private in a Chris@63: // bunch of places that don't appear to even call it, so I made it public. Oh well. Chris@63: Chris@63: template Chris@63: inline constexpr Quantity(const Quantity& other) Chris@63: : value(other.value) {} Chris@63: Chris@63: template Chris@63: inline Quantity& operator=(const Quantity& other) { Chris@63: value = other.value; Chris@63: return *this; Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Quantity Chris@63: operator+(const Quantity& other) const { Chris@63: return Quantity(value + other.value, unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr Quantity Chris@63: operator-(const Quantity& other) const { Chris@63: return Quantity(value - other.value, unsafe); Chris@63: } Chris@63: template ()>> Chris@63: inline constexpr Quantity Chris@63: operator*(OtherNumber other) const { Chris@63: return Quantity(value * other, unsafe); Chris@63: } Chris@63: template ()>> Chris@63: inline constexpr Quantity Chris@63: operator/(OtherNumber other) const { Chris@63: return Quantity(value / other, unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr decltype(Number() / OtherNumber()) Chris@63: operator/(const Quantity& other) const { Chris@63: return value / other.value; Chris@63: } Chris@63: template Chris@63: inline constexpr Quantity Chris@63: operator%(const Quantity& other) const { Chris@63: return Quantity(value % other.value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Quantity Chris@63: operator*(UnitRatio ratio) const { Chris@63: return Quantity( Chris@63: value * ratio.unit1PerUnit2, unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr Quantity Chris@63: operator/(UnitRatio ratio) const { Chris@63: return Quantity( Chris@63: value / ratio.unit1PerUnit2, unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr Quantity Chris@63: operator%(UnitRatio ratio) const { Chris@63: return Quantity( Chris@63: value % ratio.unit1PerUnit2, unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr UnitRatio Chris@63: operator/(Quantity other) const { Chris@63: return UnitRatio( Chris@63: value / other.value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr bool operator==(const Quantity& other) const { Chris@63: return value == other.value; Chris@63: } Chris@63: template Chris@63: inline constexpr bool operator!=(const Quantity& other) const { Chris@63: return value != other.value; Chris@63: } Chris@63: template Chris@63: inline constexpr bool operator<=(const Quantity& other) const { Chris@63: return value <= other.value; Chris@63: } Chris@63: template Chris@63: inline constexpr bool operator>=(const Quantity& other) const { Chris@63: return value >= other.value; Chris@63: } Chris@63: template Chris@63: inline constexpr bool operator<(const Quantity& other) const { Chris@63: return value < other.value; Chris@63: } Chris@63: template Chris@63: inline constexpr bool operator>(const Quantity& other) const { Chris@63: return value > other.value; Chris@63: } Chris@63: Chris@63: template Chris@63: inline Quantity& operator+=(const Quantity& other) { Chris@63: value += other.value; Chris@63: return *this; Chris@63: } Chris@63: template Chris@63: inline Quantity& operator-=(const Quantity& other) { Chris@63: value -= other.value; Chris@63: return *this; Chris@63: } Chris@63: template Chris@63: inline Quantity& operator*=(OtherNumber other) { Chris@63: value *= other; Chris@63: return *this; Chris@63: } Chris@63: template Chris@63: inline Quantity& operator/=(OtherNumber other) { Chris@63: value /= other.value; Chris@63: return *this; Chris@63: } Chris@63: Chris@63: private: Chris@63: Number value; Chris@63: Chris@63: template Chris@63: friend class Quantity; Chris@63: Chris@63: template Chris@63: friend inline constexpr auto operator*(Number1 a, Quantity b) Chris@63: -> Quantity; Chris@63: }; Chris@63: Chris@63: template struct Unit_ { Chris@63: static inline constexpr T get() { return T(1); } Chris@63: }; Chris@63: template Chris@63: struct Unit_> { Chris@63: static inline constexpr Quantity::get()), U> get() { Chris@63: return Quantity::get()), U>(Unit_::get(), unsafe); Chris@63: } Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr auto unit() -> decltype(Unit_::get()) { return Unit_::get(); } Chris@63: // unit>() returns a Quantity of value 1. It also, intentionally, works on basic Chris@63: // numeric types. Chris@63: Chris@63: template Chris@63: inline constexpr auto operator*(Number1 a, Quantity b) Chris@63: -> Quantity { Chris@63: return Quantity(a * b.value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr auto operator*(UnitRatio ratio, Chris@63: Quantity measure) Chris@63: -> decltype(measure * ratio) { Chris@63: return measure * ratio; Chris@63: } Chris@63: Chris@63: // ======================================================================================= Chris@63: // Absolute measures Chris@63: Chris@63: template Chris@63: class Absolute { Chris@63: // Wraps some other value -- typically a Quantity -- but represents a value measured based on Chris@63: // some absolute origin. For example, if `Duration` is a type representing a time duration, Chris@63: // Absolute might be a calendar date. Chris@63: // Chris@63: // Since Absolute represents measurements relative to some arbitrary origin, the only sensible Chris@63: // arithmetic to perform on them is addition and subtraction. Chris@63: Chris@63: // TODO(someday): Do the same automatic expansion of integer width that Quantity does? Doesn't Chris@63: // matter for our time use case, where we always use 64-bit anyway. Note that fixing this Chris@63: // would implicitly allow things like multiplying an Absolute by a UnitRatio to change its Chris@63: // units, which is actually totally logical and kind of neat. Chris@63: Chris@63: public: Chris@63: inline constexpr Absolute operator+(const T& other) const { return Absolute(value + other); } Chris@63: inline constexpr Absolute operator-(const T& other) const { return Absolute(value - other); } Chris@63: inline constexpr T operator-(const Absolute& other) const { return value - other.value; } Chris@63: Chris@63: inline Absolute& operator+=(const T& other) { value += other; return *this; } Chris@63: inline Absolute& operator-=(const T& other) { value -= other; return *this; } Chris@63: Chris@63: inline constexpr bool operator==(const Absolute& other) const { return value == other.value; } Chris@63: inline constexpr bool operator!=(const Absolute& other) const { return value != other.value; } Chris@63: inline constexpr bool operator<=(const Absolute& other) const { return value <= other.value; } Chris@63: inline constexpr bool operator>=(const Absolute& other) const { return value >= other.value; } Chris@63: inline constexpr bool operator< (const Absolute& other) const { return value < other.value; } Chris@63: inline constexpr bool operator> (const Absolute& other) const { return value > other.value; } Chris@63: Chris@63: private: Chris@63: T value; Chris@63: Chris@63: explicit constexpr Absolute(T value): value(value) {} Chris@63: Chris@63: template Chris@63: friend inline constexpr U origin(); Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr Absolute operator+(const T& a, const Absolute& b) { Chris@63: return b + a; Chris@63: } Chris@63: Chris@63: template struct UnitOf_ { typedef T Type; }; Chris@63: template struct UnitOf_> { typedef T Type; }; Chris@63: template Chris@63: using UnitOf = typename UnitOf_::Type; Chris@63: // UnitOf> is T. UnitOf is AnythingElse. Chris@63: Chris@63: template Chris@63: inline constexpr T origin() { return T(0 * unit>()); } Chris@63: // origin>() returns an Absolute of value 0. It also, intentionally, works on basic Chris@63: // numeric types. Chris@63: Chris@63: // ======================================================================================= Chris@63: // Overflow avoidance Chris@63: Chris@63: template Chris@63: struct BitCount_ { Chris@63: static constexpr uint value = BitCount_<(n >> 1), accum + 1>::value; Chris@63: }; Chris@63: template Chris@63: struct BitCount_<0, accum> { Chris@63: static constexpr uint value = accum; Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr uint bitCount() { return BitCount_::value; } Chris@63: // Number of bits required to represent the number `n`. Chris@63: Chris@63: template struct AtLeastUInt_ { Chris@63: static_assert(bitCountBitCount < 7, "don't know how to represent integers over 64 bits"); Chris@63: }; Chris@63: template <> struct AtLeastUInt_<0> { typedef uint8_t Type; }; Chris@63: template <> struct AtLeastUInt_<1> { typedef uint8_t Type; }; Chris@63: template <> struct AtLeastUInt_<2> { typedef uint8_t Type; }; Chris@63: template <> struct AtLeastUInt_<3> { typedef uint8_t Type; }; Chris@63: template <> struct AtLeastUInt_<4> { typedef uint16_t Type; }; Chris@63: template <> struct AtLeastUInt_<5> { typedef uint32_t Type; }; Chris@63: template <> struct AtLeastUInt_<6> { typedef uint64_t Type; }; Chris@63: Chris@63: template Chris@63: using AtLeastUInt = typename AtLeastUInt_()>::Type; Chris@63: // AtLeastUInt is an unsigned integer of at least n bits. E.g. AtLeastUInt<12> is uint16_t. Chris@63: Chris@63: // ------------------------------------------------------------------- Chris@63: Chris@63: template Chris@63: class BoundedConst { Chris@63: // A constant integer value on which we can do bit size analysis. Chris@63: Chris@63: public: Chris@63: BoundedConst() = default; Chris@63: Chris@63: inline constexpr uint unwrap() const { return value; } Chris@63: Chris@63: #define OP(op, check) \ Chris@63: template \ Chris@63: inline constexpr BoundedConst<(value op other)> \ Chris@63: operator op(BoundedConst) const { \ Chris@63: static_assert(check, "overflow in BoundedConst arithmetic"); \ Chris@63: return BoundedConst<(value op other)>(); \ Chris@63: } Chris@63: #define COMPARE_OP(op) \ Chris@63: template \ Chris@63: inline constexpr bool operator op(BoundedConst) const { \ Chris@63: return value op other; \ Chris@63: } Chris@63: Chris@63: OP(+, value + other >= value) Chris@63: OP(-, value - other <= value) Chris@63: OP(*, value * other / other == value) Chris@63: OP(/, true) // div by zero already errors out; no other division ever overflows Chris@63: OP(%, true) // mod by zero already errors out; no other modulus ever overflows Chris@63: OP(<<, value << other >= value) Chris@63: OP(>>, true) // right shift can't overflow Chris@63: OP(&, true) // bitwise ops can't overflow Chris@63: OP(|, true) // bitwise ops can't overflow Chris@63: Chris@63: COMPARE_OP(==) Chris@63: COMPARE_OP(!=) Chris@63: COMPARE_OP(< ) Chris@63: COMPARE_OP(> ) Chris@63: COMPARE_OP(<=) Chris@63: COMPARE_OP(>=) Chris@63: #undef OP Chris@63: #undef COMPARE_OP Chris@63: }; Chris@63: Chris@63: template Chris@63: struct Unit_> { Chris@63: static inline constexpr BoundedConst<1> get() { return BoundedConst<1>(); } Chris@63: }; Chris@63: Chris@63: template Chris@63: struct Unit_> { Chris@63: static inline constexpr BoundedConst<1> get() { return BoundedConst<1>(); } Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr BoundedConst bounded() { Chris@63: return BoundedConst(); Chris@63: } Chris@63: Chris@63: template Chris@63: static constexpr uint64_t boundedAdd() { Chris@63: static_assert(a + b >= a, "possible overflow detected"); Chris@63: return a + b; Chris@63: } Chris@63: template Chris@63: static constexpr uint64_t boundedSub() { Chris@63: static_assert(a - b <= a, "possible underflow detected"); Chris@63: return a - b; Chris@63: } Chris@63: template Chris@63: static constexpr uint64_t boundedMul() { Chris@63: static_assert(a * b / b == a, "possible overflow detected"); Chris@63: return a * b; Chris@63: } Chris@63: template Chris@63: static constexpr uint64_t boundedLShift() { Chris@63: static_assert(a << b >= a, "possible overflow detected"); Chris@63: return a << b; Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr BoundedConst min(BoundedConst, BoundedConst) { Chris@63: return bounded(); Chris@63: } Chris@63: template Chris@63: inline constexpr BoundedConst max(BoundedConst, BoundedConst) { Chris@63: return bounded(); Chris@63: } Chris@63: // We need to override min() and max() between constants because the ternary operator in the Chris@63: // default implementation would complain. Chris@63: Chris@63: // ------------------------------------------------------------------- Chris@63: Chris@63: template Chris@63: class Bounded { Chris@63: public: Chris@63: static_assert(maxN <= T(kj::maxValue), "possible overflow detected"); Chris@63: Chris@63: Bounded() = default; Chris@63: Chris@63: Bounded(const Bounded& other) = default; Chris@63: template ()>> Chris@63: inline constexpr Bounded(OtherInt value): value(value) { Chris@63: static_assert(OtherInt(maxValue) <= maxN, "possible overflow detected"); Chris@63: } Chris@63: template Chris@63: inline constexpr Bounded(const Bounded& other) Chris@63: : value(other.value) { Chris@63: static_assert(otherMax <= maxN, "possible overflow detected"); Chris@63: } Chris@63: template Chris@63: inline constexpr Bounded(BoundedConst) Chris@63: : value(otherValue) { Chris@63: static_assert(otherValue <= maxN, "overflow detected"); Chris@63: } Chris@63: Chris@63: Bounded& operator=(const Bounded& other) = default; Chris@63: template ()>> Chris@63: Bounded& operator=(OtherInt other) { Chris@63: static_assert(OtherInt(maxValue) <= maxN, "possible overflow detected"); Chris@63: value = other; Chris@63: return *this; Chris@63: } Chris@63: template Chris@63: inline Bounded& operator=(const Bounded& other) { Chris@63: static_assert(otherMax <= maxN, "possible overflow detected"); Chris@63: value = other.value; Chris@63: return *this; Chris@63: } Chris@63: template Chris@63: inline Bounded& operator=(BoundedConst) { Chris@63: static_assert(otherValue <= maxN, "overflow detected"); Chris@63: value = otherValue; Chris@63: return *this; Chris@63: } Chris@63: Chris@63: inline constexpr T unwrap() const { return value; } Chris@63: Chris@63: #define OP(op, newMax) \ Chris@63: template \ Chris@63: inline constexpr Bounded \ Chris@63: operator op(const Bounded& other) const { \ Chris@63: return Bounded(value op other.value, unsafe); \ Chris@63: } Chris@63: #define COMPARE_OP(op) \ Chris@63: template \ Chris@63: inline constexpr bool operator op(const Bounded& other) const { \ Chris@63: return value op other.value; \ Chris@63: } Chris@63: Chris@63: OP(+, (boundedAdd())) Chris@63: OP(*, (boundedMul())) Chris@63: OP(/, maxN) Chris@63: OP(%, otherMax - 1) Chris@63: Chris@63: // operator- is intentionally omitted because we mostly use this with unsigned types, and Chris@63: // subtraction requires proof that subtrahend is not greater than the minuend. Chris@63: Chris@63: COMPARE_OP(==) Chris@63: COMPARE_OP(!=) Chris@63: COMPARE_OP(< ) Chris@63: COMPARE_OP(> ) Chris@63: COMPARE_OP(<=) Chris@63: COMPARE_OP(>=) Chris@63: Chris@63: #undef OP Chris@63: #undef COMPARE_OP Chris@63: Chris@63: template Chris@63: inline Bounded assertMax(ErrorFunc&& func) const { Chris@63: // Assert that the number is no more than `newMax`. Otherwise, call `func`. Chris@63: static_assert(newMax < maxN, "this bounded size assertion is redundant"); Chris@63: if (KJ_UNLIKELY(value > newMax)) func(); Chris@63: return Bounded(value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Bounded subtractChecked( Chris@63: const Bounded& other, ErrorFunc&& func) const { Chris@63: // Subtract a number, calling func() if the result would underflow. Chris@63: if (KJ_UNLIKELY(value < other.value)) func(); Chris@63: return Bounded(value - other.value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Bounded subtractChecked( Chris@63: BoundedConst, ErrorFunc&& func) const { Chris@63: // Subtract a number, calling func() if the result would underflow. Chris@63: static_assert(otherValue <= maxN, "underflow detected"); Chris@63: if (KJ_UNLIKELY(value < otherValue)) func(); Chris@63: return Bounded(value - otherValue, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Maybe> trySubtract( Chris@63: const Bounded& other) const { Chris@63: // Subtract a number, calling func() if the result would underflow. Chris@63: if (value < other.value) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return Bounded(value - other.value, unsafe); Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: inline Maybe> trySubtract(BoundedConst) const { Chris@63: // Subtract a number, calling func() if the result would underflow. Chris@63: if (value < otherValue) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return Bounded(value - otherValue, unsafe); Chris@63: } Chris@63: } Chris@63: Chris@63: inline constexpr Bounded(T value, decltype(unsafe)): value(value) {} Chris@63: template Chris@63: inline constexpr Bounded(Bounded value, decltype(unsafe)) Chris@63: : value(value.value) {} Chris@63: // Mainly for internal use. Chris@63: // Chris@63: // Only use these as a last resort, with ample commentary on why you think it's safe. Chris@63: Chris@63: private: Chris@63: T value; Chris@63: Chris@63: template Chris@63: friend class Bounded; Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr Bounded bounded(Number value) { Chris@63: return Bounded(value, unsafe); Chris@63: } Chris@63: Chris@63: inline constexpr Bounded<1, uint8_t> bounded(bool value) { Chris@63: return Bounded<1, uint8_t>(value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded(), Number> assumeBits(Number value) { Chris@63: return Bounded(), Number>(value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded(), T> assumeBits(Bounded value) { Chris@63: return Bounded(), T>(value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr auto assumeBits(Quantity value) Chris@63: -> Quantity(value / unit>())), Unit> { Chris@63: return Quantity(value / unit>())), Unit>( Chris@63: assumeBits(value / unit>()), unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded assumeMax(Number value) { Chris@63: return Bounded(value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded assumeMax(Bounded value) { Chris@63: return Bounded(value, unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr auto assumeMax(Quantity value) Chris@63: -> Quantity(value / unit>())), Unit> { Chris@63: return Quantity(value / unit>())), Unit>( Chris@63: assumeMax(value / unit>()), unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded assumeMax(BoundedConst, Number value) { Chris@63: return assumeMax(value); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded assumeMax(BoundedConst, Bounded value) { Chris@63: return assumeMax(value); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr auto assumeMax(Quantity, Unit>, Quantity value) Chris@63: -> decltype(assumeMax(value)) { Chris@63: return assumeMax(value); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Bounded assertMax(Bounded value, ErrorFunc&& errorFunc) { Chris@63: // Assert that the bounded value is less than or equal to the given maximum, calling errorFunc() Chris@63: // if not. Chris@63: static_assert(newMax < maxN, "this bounded size assertion is redundant"); Chris@63: return value.template assertMax(kj::fwd(errorFunc)); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Quantity, Unit> assertMax( Chris@63: Quantity, Unit> value, ErrorFunc&& errorFunc) { Chris@63: // Assert that the bounded value is less than or equal to the given maximum, calling errorFunc() Chris@63: // if not. Chris@63: static_assert(newMax < maxN, "this bounded size assertion is redundant"); Chris@63: return (value / unit()).template assertMax( Chris@63: kj::fwd(errorFunc)) * unit(); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Bounded assertMax( Chris@63: BoundedConst, Bounded value, ErrorFunc&& errorFunc) { Chris@63: return assertMax(value, kj::mv(errorFunc)); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Quantity, Unit> assertMax( Chris@63: Quantity, Unit>, Chris@63: Quantity, Unit> value, ErrorFunc&& errorFunc) { Chris@63: return assertMax(value, kj::mv(errorFunc)); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Bounded(), T> assertMaxBits( Chris@63: Bounded value, ErrorFunc&& errorFunc = ErrorFunc()) { Chris@63: // Assert that the bounded value requires no more than the given number of bits, calling Chris@63: // errorFunc() if not. Chris@63: return assertMax()>(value, kj::fwd(errorFunc)); Chris@63: } Chris@63: Chris@63: template Chris@63: inline Quantity(), T>, Unit> assertMaxBits( Chris@63: Quantity, Unit> value, ErrorFunc&& errorFunc = ErrorFunc()) { Chris@63: // Assert that the bounded value requires no more than the given number of bits, calling Chris@63: // errorFunc() if not. Chris@63: return assertMax()>(value, kj::fwd(errorFunc)); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded upgradeBound(Bounded value) { Chris@63: return value; Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Quantity, Unit> upgradeBound( Chris@63: Quantity, Unit> value) { Chris@63: return value; Chris@63: } Chris@63: Chris@63: template Chris@63: inline auto subtractChecked(Bounded value, Other other, ErrorFunc&& errorFunc) Chris@63: -> decltype(value.subtractChecked(other, kj::fwd(errorFunc))) { Chris@63: return value.subtractChecked(other, kj::fwd(errorFunc)); Chris@63: } Chris@63: Chris@63: template Chris@63: inline auto subtractChecked(Quantity value, Quantity other, ErrorFunc&& errorFunc) Chris@63: -> Quantity(errorFunc))), Unit> { Chris@63: return subtractChecked(value / unit>(), Chris@63: other / unit>(), Chris@63: kj::fwd(errorFunc)) Chris@63: * unit>(); Chris@63: } Chris@63: Chris@63: template Chris@63: inline auto trySubtract(Bounded value, Other other) Chris@63: -> decltype(value.trySubtract(other)) { Chris@63: return value.trySubtract(other); Chris@63: } Chris@63: Chris@63: template Chris@63: inline auto trySubtract(Quantity value, Quantity other) Chris@63: -> Maybe> { Chris@63: return trySubtract(value / unit>(), Chris@63: other / unit>()) Chris@63: .map([](decltype(subtractChecked(T(), U(), int())) x) { Chris@63: return x * unit>(); Chris@63: }); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded> Chris@63: min(Bounded a, Bounded b) { Chris@63: return Bounded>(kj::min(a.unwrap(), b.unwrap()), unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr Bounded> Chris@63: max(Bounded a, Bounded b) { Chris@63: return Bounded>(kj::max(a.unwrap(), b.unwrap()), unsafe); Chris@63: } Chris@63: // We need to override min() and max() because: Chris@63: // 1) WiderType<> might not choose the correct bounds. Chris@63: // 2) One of the two sides of the ternary operator in the default implementation would fail to Chris@63: // typecheck even though it is OK in practice. Chris@63: Chris@63: // ------------------------------------------------------------------- Chris@63: // Operators between Bounded and BoundedConst Chris@63: Chris@63: #define OP(op, newMax) \ Chris@63: template \ Chris@63: inline constexpr Bounded<(newMax), decltype(T() op uint())> operator op( \ Chris@63: Bounded value, BoundedConst) { \ Chris@63: return Bounded<(newMax), decltype(T() op uint())>(value.unwrap() op cvalue, unsafe); \ Chris@63: } Chris@63: Chris@63: #define REVERSE_OP(op, newMax) \ Chris@63: template \ Chris@63: inline constexpr Bounded<(newMax), decltype(uint() op T())> operator op( \ Chris@63: BoundedConst, Bounded value) { \ Chris@63: return Bounded<(newMax), decltype(uint() op T())>(cvalue op value.unwrap(), unsafe); \ Chris@63: } Chris@63: Chris@63: #define COMPARE_OP(op) \ Chris@63: template \ Chris@63: inline constexpr bool operator op(Bounded value, BoundedConst) { \ Chris@63: return value.unwrap() op cvalue; \ Chris@63: } \ Chris@63: template \ Chris@63: inline constexpr bool operator op(BoundedConst, Bounded value) { \ Chris@63: return cvalue op value.unwrap(); \ Chris@63: } Chris@63: Chris@63: OP(+, (boundedAdd())) Chris@63: REVERSE_OP(+, (boundedAdd())) Chris@63: Chris@63: OP(*, (boundedMul())) Chris@63: REVERSE_OP(*, (boundedAdd())) Chris@63: Chris@63: OP(/, maxN / cvalue) Chris@63: REVERSE_OP(/, cvalue) // denominator could be 1 Chris@63: Chris@63: OP(%, cvalue - 1) Chris@63: REVERSE_OP(%, maxN - 1) Chris@63: Chris@63: OP(<<, (boundedLShift())) Chris@63: REVERSE_OP(<<, (boundedLShift())) Chris@63: Chris@63: OP(>>, maxN >> cvalue) Chris@63: REVERSE_OP(>>, cvalue >> maxN) Chris@63: Chris@63: OP(&, maxValueForBits()>() & cvalue) Chris@63: REVERSE_OP(&, maxValueForBits()>() & cvalue) Chris@63: Chris@63: OP(|, maxN | cvalue) Chris@63: REVERSE_OP(|, maxN | cvalue) Chris@63: Chris@63: COMPARE_OP(==) Chris@63: COMPARE_OP(!=) Chris@63: COMPARE_OP(< ) Chris@63: COMPARE_OP(> ) Chris@63: COMPARE_OP(<=) Chris@63: COMPARE_OP(>=) Chris@63: Chris@63: #undef OP Chris@63: #undef REVERSE_OP Chris@63: #undef COMPARE_OP Chris@63: Chris@63: template Chris@63: inline constexpr Bounded Chris@63: operator-(BoundedConst, Bounded value) { Chris@63: // We allow subtraction of a variable from a constant only if the constant is greater than or Chris@63: // equal to the maximum possible value of the variable. Since the variable could be zero, the Chris@63: // result can be as large as the constant. Chris@63: // Chris@63: // We do not allow subtraction of a constant from a variable because there's never a guarantee it Chris@63: // won't underflow (unless the constant is zero, which is silly). Chris@63: static_assert(cvalue >= maxN, "possible underflow detected"); Chris@63: return Bounded(cvalue - value.unwrap(), unsafe); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Bounded min(Bounded a, BoundedConst) { Chris@63: return Bounded(kj::min(b, a.unwrap()), unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr Bounded min(BoundedConst, Bounded a) { Chris@63: return Bounded(kj::min(a.unwrap(), b), unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr Bounded max(Bounded a, BoundedConst) { Chris@63: return Bounded(kj::max(b, a.unwrap()), unsafe); Chris@63: } Chris@63: template Chris@63: inline constexpr Bounded max(BoundedConst, Bounded a) { Chris@63: return Bounded(kj::max(a.unwrap(), b), unsafe); Chris@63: } Chris@63: // We need to override min() between a Bounded and a constant since: Chris@63: // 1) WiderType<> might choose BoundedConst over a 1-byte Bounded, which is wrong. Chris@63: // 2) To clamp the bounds of the output type. Chris@63: // 3) Same ternary operator typechecking issues. Chris@63: Chris@63: // ------------------------------------------------------------------- Chris@63: Chris@63: template Chris@63: class SafeUnwrapper { Chris@63: public: Chris@63: inline explicit constexpr SafeUnwrapper(Bounded value): value(value.unwrap()) {} Chris@63: Chris@63: template ()>> Chris@63: inline constexpr operator U() const { Chris@63: static_assert(maxN <= U(maxValue), "possible truncation detected"); Chris@63: return value; Chris@63: } Chris@63: Chris@63: inline constexpr operator bool() const { Chris@63: static_assert(maxN <= 1, "possible truncation detected"); Chris@63: return value; Chris@63: } Chris@63: Chris@63: private: Chris@63: T value; Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr SafeUnwrapper unbound(Bounded bounded) { Chris@63: // Unwraps the bounded value, returning a value that can be implicitly cast to any integer type. Chris@63: // If this implicit cast could truncate, a compile-time error will be raised. Chris@63: return SafeUnwrapper(bounded); Chris@63: } Chris@63: Chris@63: template Chris@63: class SafeConstUnwrapper { Chris@63: public: Chris@63: template ()>> Chris@63: inline constexpr operator T() const { Chris@63: static_assert(value <= T(maxValue), "this operation will truncate"); Chris@63: return value; Chris@63: } Chris@63: Chris@63: inline constexpr operator bool() const { Chris@63: static_assert(value <= 1, "this operation will truncate"); Chris@63: return value; Chris@63: } Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr SafeConstUnwrapper unbound(BoundedConst) { Chris@63: return SafeConstUnwrapper(); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr T unboundAs(U value) { Chris@63: return unbound(value); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr T unboundMax(Bounded value) { Chris@63: // Explicitly ungaurd expecting a value that is at most `maxN`. Chris@63: static_assert(maxN <= requestedMax, "possible overflow detected"); Chris@63: return value.unwrap(); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr uint unboundMax(BoundedConst) { Chris@63: // Explicitly ungaurd expecting a value that is at most `maxN`. Chris@63: static_assert(value <= requestedMax, "overflow detected"); Chris@63: return value; Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr auto unboundMaxBits(T value) -> Chris@63: decltype(unboundMax()>(value)) { Chris@63: // Explicitly ungaurd expecting a value that fits into `bits` bits. Chris@63: return unboundMax()>(value); Chris@63: } Chris@63: Chris@63: #define OP(op) \ Chris@63: template \ Chris@63: inline constexpr auto operator op(T a, SafeUnwrapper b) -> decltype(a op (T)b) { \ Chris@63: return a op (AtLeastUInt)b; \ Chris@63: } \ Chris@63: template \ Chris@63: inline constexpr auto operator op(SafeUnwrapper b, T a) -> decltype((T)b op a) { \ Chris@63: return (AtLeastUInt)b op a; \ Chris@63: } \ Chris@63: template \ Chris@63: inline constexpr auto operator op(T a, SafeConstUnwrapper b) -> decltype(a op (T)b) { \ Chris@63: return a op (AtLeastUInt)b; \ Chris@63: } \ Chris@63: template \ Chris@63: inline constexpr auto operator op(SafeConstUnwrapper b, T a) -> decltype((T)b op a) { \ Chris@63: return (AtLeastUInt)b op a; \ Chris@63: } Chris@63: Chris@63: OP(+) Chris@63: OP(-) Chris@63: OP(*) Chris@63: OP(/) Chris@63: OP(%) Chris@63: OP(<<) Chris@63: OP(>>) Chris@63: OP(&) Chris@63: OP(|) Chris@63: OP(==) Chris@63: OP(!=) Chris@63: OP(<=) Chris@63: OP(>=) Chris@63: OP(<) Chris@63: OP(>) Chris@63: Chris@63: #undef OP Chris@63: Chris@63: // ------------------------------------------------------------------- Chris@63: Chris@63: template Chris@63: class Range> { Chris@63: public: Chris@63: inline constexpr Range(Bounded begin, Bounded end) Chris@63: : inner(unbound(begin), unbound(end)) {} Chris@63: inline explicit constexpr Range(Bounded end) Chris@63: : inner(unbound(end)) {} Chris@63: Chris@63: class Iterator { Chris@63: public: Chris@63: Iterator() = default; Chris@63: inline explicit Iterator(typename Range::Iterator inner): inner(inner) {} Chris@63: Chris@63: inline Bounded operator* () const { return Bounded(*inner, unsafe); } Chris@63: inline Iterator& operator++() { ++inner; return *this; } Chris@63: Chris@63: inline bool operator==(const Iterator& other) const { return inner == other.inner; } Chris@63: inline bool operator!=(const Iterator& other) const { return inner != other.inner; } Chris@63: Chris@63: private: Chris@63: typename Range::Iterator inner; Chris@63: }; Chris@63: Chris@63: inline Iterator begin() const { return Iterator(inner.begin()); } Chris@63: inline Iterator end() const { return Iterator(inner.end()); } Chris@63: Chris@63: private: Chris@63: Range inner; Chris@63: }; Chris@63: Chris@63: template Chris@63: class Range> { Chris@63: public: Chris@63: inline constexpr Range(Quantity begin, Quantity end) Chris@63: : inner(begin / unit>(), end / unit>()) {} Chris@63: inline explicit constexpr Range(Quantity end) Chris@63: : inner(end / unit>()) {} Chris@63: Chris@63: class Iterator { Chris@63: public: Chris@63: Iterator() = default; Chris@63: inline explicit Iterator(typename Range::Iterator inner): inner(inner) {} Chris@63: Chris@63: inline Quantity operator* () const { return *inner * unit>(); } Chris@63: inline Iterator& operator++() { ++inner; return *this; } Chris@63: Chris@63: inline bool operator==(const Iterator& other) const { return inner == other.inner; } Chris@63: inline bool operator!=(const Iterator& other) const { return inner != other.inner; } Chris@63: Chris@63: private: Chris@63: typename Range::Iterator inner; Chris@63: }; Chris@63: Chris@63: inline Iterator begin() const { return Iterator(inner.begin()); } Chris@63: inline Iterator end() const { return Iterator(inner.end()); } Chris@63: Chris@63: private: Chris@63: Range inner; Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr Range> zeroTo(BoundedConst end) { Chris@63: return Range>(end); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Range, Unit>> Chris@63: zeroTo(Quantity, Unit> end) { Chris@63: return Range, Unit>>(end); Chris@63: } Chris@63: Chris@63: } // namespace kj Chris@63: Chris@63: #endif // KJ_UNITS_H_