clamp.h 746 B

12345678910111213141516171819202122232425262728293031
  1. //
  2. // clamp.h
  3. // limit
  4. //
  5. // Created by Sam Jaffe on 12/9/23.
  6. //
  7. #pragma once
  8. #include <algorithm>
  9. #include <stdexcept>
  10. #include <utility>
  11. namespace math {
  12. template <typename T, typename Bound>
  13. decltype(auto) clamp(T const & value, Bound const & lower, Bound const & upper) {
  14. using std::min;
  15. using std::max;
  16. return max(min(value, upper), lower);
  17. }
  18. template <typename T, typename Bound>
  19. T const & assert_in_bounds(T const & value, Bound const & lower, Bound const & upper) {
  20. if (lower > upper) {
  21. throw std::domain_error("The minimum value must be less than or equal to the maximum");
  22. } else if (clamp(value, lower, upper) != value) {
  23. throw std::out_of_range("Must construct a value within range");
  24. }
  25. return value;
  26. }
  27. }