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