Spicy
enum.h
1 #pragma once
2 
3 #include <algorithm>
4 #include <limits>
5 #include <string>
6 #include <type_traits>
7 #include <variant>
8 
9 #include <hilti/rt/exception.h>
10 #include <hilti/rt/logging.h>
11 #include <hilti/rt/type-info.h>
12 
13 namespace hilti::rt::enum_ {
14 
22 template<typename T>
23 bool has_label(const T& t, const TypeInfo* ti) {
24  if ( ti->tag != TypeInfo::Enum )
25  internalError("unexpected type info in enum_::has_label");
26 
27  const auto& labels = ti->enum_->labels();
28  return std::any_of(labels.begin(), labels.end(),
29  [&](const auto& l) { return l.value != -1 && static_cast<int64_t>(t) == l.value; });
30 }
31 
41 template<typename T>
42 T from_int(int64_t n) {
43  static_assert(std::is_enum<T>::value && std::is_same_v<std::underlying_type_t<T>, int64_t>);
44  return static_cast<T>(n);
45 }
46 
59 template<typename T>
60 T from_uint(uint64_t n) {
61  static_assert(std::is_enum<T>::value && std::is_same_v<std::underlying_type_t<T>, int64_t>);
62 
63  if ( n > static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) )
64  throw InvalidValue("enum value exceeds range");
65 
66  return static_cast<T>(n);
67 }
68 
69 } // namespace hilti::rt::enum_
void internalError(const std::string &msg) __attribute__((noreturn))
Definition: logging.cc:17
Definition: enum.h:13