blob: 5e8ef819d3a2f6a73ef026aad24eb2234c925531 [file] [log] [blame]
Wludzik, Jozefd960e1f2021-01-08 09:25:59 +01001#pragma once
2
Krzysztof Grobelnye8fc5752021-02-05 14:30:45 +00003#include <algorithm>
4#include <array>
Wludzik, Jozefd960e1f2021-01-08 09:25:59 +01005#include <stdexcept>
Krzysztof Grobelnye8fc5752021-02-05 14:30:45 +00006#include <string>
Wludzik, Jozefd960e1f2021-01-08 09:25:59 +01007
8namespace utils
9{
10
11template <class T, T first, T last>
Krzysztof Grobelnye8fc5752021-02-05 14:30:45 +000012inline T toEnum(std::underlying_type_t<T> x)
Wludzik, Jozefd960e1f2021-01-08 09:25:59 +010013{
Krzysztof Grobelnye8fc5752021-02-05 14:30:45 +000014 if (x < static_cast<std::underlying_type_t<T>>(first) ||
15 x > static_cast<std::underlying_type_t<T>>(last))
Wludzik, Jozefd960e1f2021-01-08 09:25:59 +010016 {
17 throw std::out_of_range("Value is not in range of enum");
18 }
19 return static_cast<T>(x);
20}
Krzysztof Grobelnye8fc5752021-02-05 14:30:45 +000021
22template <class T>
23inline std::underlying_type_t<T> toUnderlying(T value)
24{
25 return static_cast<std::underlying_type_t<T>>(value);
26}
27
28template <class T, size_t N>
29inline T stringToEnum(const std::array<std::pair<std::string_view, T>, N>& data,
30 const std::string& value)
31{
32 auto it = std::find_if(
33 std::begin(data), std::end(data),
34 [&value](const auto& item) { return item.first == value; });
35 if (it == std::end(data))
36 {
37 throw std::out_of_range("Value is not in range of enum");
38 }
39 return it->second;
40}
41
42template <class T, size_t N>
43inline std::string_view
44 enumToString(const std::array<std::pair<std::string_view, T>, N>& data,
45 T value)
46{
47 auto it = std::find_if(
48 std::begin(data), std::end(data),
49 [value](const auto& item) { return item.second == value; });
50 if (it == std::end(data))
51 {
52 throw std::out_of_range("Value is not in range of enum");
53 }
54 return it->first;
55}
56
Wludzik, Jozefd960e1f2021-01-08 09:25:59 +010057} // namespace utils