| 12345678910111213141516171819202122232425262728293031 |
- //
- // clamp.h
- // limit
- //
- // Created by Sam Jaffe on 12/9/23.
- //
- #pragma once
- #include <algorithm>
- #include <stdexcept>
- #include <utility>
- namespace math {
- template <typename T, typename Bound>
- decltype(auto) clamp(T const & value, Bound const & lower, Bound const & upper) {
- using std::min;
- using std::max;
- return max(min(value, upper), lower);
- }
- template <typename T, typename Bound>
- T const & assert_in_bounds(T const & value, Bound const & lower, Bound const & upper) {
- if (lower > upper) {
- throw std::domain_error("The minimum value must be less than or equal to the maximum");
- } else if (clamp(value, lower, upper) != value) {
- throw std::out_of_range("Must construct a value within range");
- }
- return value;
- }
- }
|