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 && t.value() == l.value; });
30 }
31 
41 template<typename T>
42 T from_int(int64_t n) {
43  using Value = typename T::Value;
44  static_assert(std::is_enum_v<Value>);
45  static_assert(std::is_same_v<std::underlying_type_t<Value>, int64_t>);
46  return static_cast<T>(n);
47 }
48 
61 template<typename T>
62 T from_uint(uint64_t n) {
63  using Value = typename T::Value;
64  static_assert(std::is_enum_v<Value>);
65  static_assert(std::is_same_v<std::underlying_type_t<Value>, int64_t>);
66 
67  if ( n > static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) )
68  throw InvalidValue("enum value exceeds range");
69 
70  return static_cast<T>(n);
71 }
72 
73 } // namespace hilti::rt::enum_
void internalError(const std::string &msg) __attribute__((noreturn))
Definition: logging.cc:16
Definition: enum.h:13