| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- //
- // limit.h
- // utilities
- //
- // Created by Sam Jaffe on 10/22/13.
- // Copyright (c) 2013 Sam Jaffe. All rights reserved.
- //
- #pragma once
- #include <stdexcept>
- namespace math {
- struct {} assert_bounds;
- using AssertBounds = decltype(assert_bounds);
- template <typename T, T MINIMUM_VALUE, T MAXIMUM_VALUE>
- class Bound final {
- private:
- public:
- static_assert(MINIMUM_VALUE <= MAXIMUM_VALUE,
- "The minimum value must be less than or equal to the maximum");
-
- typedef Tp value_type;
- static constexpr const value_type min = MINIMUM_VALUE;
- static constexpr const value_type max = MAXIMUM_VALUE;
-
- constexpr Bound() = default;
- constexpr Bound(value_type const & val) noexcept
- : value(std::max(min, std::min(max, val))) {}
-
- Bound(AssertBounds, value_type val) : value(val) {
- if (val < min || max < val) {
- throw std::out_of_range{"Must construct a value within range"};
- }
- }
-
- Bound& operator-=(value_type v) { return *this = Bound(value - v); }
- Bound& operator+=(value_type v) { return *this = Bound(value + v); }
- Bound& operator--() { return *this -= 1; }
- Bound& operator++() { return *this += 1; }
-
- Bound operator--(int) {
- Bound tmp = *this;
- operator--();
- return tmp;
- }
-
- Bound operator++(int) {
- Bound tmp = *this;
- operator++();
- return tmp;
- }
-
- operator value_type() const { return value; }
-
- private:
- value_type value{};
- };
- template <typename T, T MINMAX> using SymBound = Bound<T, -MINMAX, +MINMAX>;
- template <typename T, T VAL>
- using UniBound = std::conditional_t<0 <= VAL, Bound<T, 0, VAL>, Bound<T, VAL, 0>>;
- template <typename L, L l1, L h1, typename R, R l2, R h2>
- auto operator+(Bound<L, l1, h1> lhs, Bound<R, l2, h2> rhs) {
- return L(lhs) + R(rhs);
- }
- template <typename L, L l1, L h1, typename R, R l2, R h2>
- auto operator-(Bound<L, l1, h1> lhs, Bound<R, l2, h2> rhs) {
- return L(lhs) - R(rhs);
- }
- template <typename L, L l1, L h1, typename R, R l2, R h2>
- auto operator*(Bound<L, l1, h1> lhs, Bound<R, l2, h2> rhs) {
- return L(lhs) * R(rhs);
- }
- template <typename L, L l1, L h1, typename R, R l2, R h2>
- auto operator/(Bound<L, l1, h1> lhs, Bound<R, l2, h2> rhs) {
- return L(lhs) / R(rhs);
- }
- }
|