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