optional_index.hpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2019 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_HISTOGRAM_DETAIL_OPTIONAL_INDEX_HPP
  7. #define BOOST_HISTOGRAM_DETAIL_OPTIONAL_INDEX_HPP
  8. #include <cassert>
  9. #include <cstdint>
  10. namespace boost {
  11. namespace histogram {
  12. namespace detail {
  13. constexpr auto invalid_index = ~static_cast<std::size_t>(0);
  14. // integer with a persistent invalid state, similar to NaN
  15. struct optional_index {
  16. std::size_t value;
  17. optional_index& operator=(std::size_t x) noexcept {
  18. value = x;
  19. return *this;
  20. }
  21. optional_index& operator+=(std::intptr_t x) noexcept {
  22. assert(x >= 0 || static_cast<std::size_t>(-x) <= value);
  23. if (value != invalid_index) { value += x; }
  24. return *this;
  25. }
  26. optional_index& operator+=(const optional_index& x) noexcept {
  27. if (value != invalid_index) return operator+=(x.value);
  28. value = invalid_index;
  29. return *this;
  30. }
  31. operator std::size_t() const noexcept { return value; }
  32. friend bool operator<=(std::size_t x, optional_index idx) noexcept {
  33. return x <= idx.value;
  34. }
  35. };
  36. constexpr inline bool is_valid(const std::size_t) noexcept { return true; }
  37. inline bool is_valid(const optional_index x) noexcept { return x.value != invalid_index; }
  38. } // namespace detail
  39. } // namespace histogram
  40. } // namespace boost
  41. #endif