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