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