Wludzik, Jozef | d960e1f | 2021-01-08 09:25:59 +0100 | [diff] [blame] | 1 | #pragma once |
| 2 | |
Krzysztof Grobelny | e8fc575 | 2021-02-05 14:30:45 +0000 | [diff] [blame] | 3 | #include <algorithm> |
| 4 | #include <array> |
Wludzik, Jozef | d960e1f | 2021-01-08 09:25:59 +0100 | [diff] [blame] | 5 | #include <stdexcept> |
Krzysztof Grobelny | e8fc575 | 2021-02-05 14:30:45 +0000 | [diff] [blame] | 6 | #include <string> |
Wludzik, Jozef | d960e1f | 2021-01-08 09:25:59 +0100 | [diff] [blame] | 7 | |
| 8 | namespace utils |
| 9 | { |
| 10 | |
| 11 | template <class T, T first, T last> |
Krzysztof Grobelny | e8fc575 | 2021-02-05 14:30:45 +0000 | [diff] [blame] | 12 | inline T toEnum(std::underlying_type_t<T> x) |
Wludzik, Jozef | d960e1f | 2021-01-08 09:25:59 +0100 | [diff] [blame] | 13 | { |
Krzysztof Grobelny | e8fc575 | 2021-02-05 14:30:45 +0000 | [diff] [blame] | 14 | if (x < static_cast<std::underlying_type_t<T>>(first) || |
| 15 | x > static_cast<std::underlying_type_t<T>>(last)) |
Wludzik, Jozef | d960e1f | 2021-01-08 09:25:59 +0100 | [diff] [blame] | 16 | { |
| 17 | throw std::out_of_range("Value is not in range of enum"); |
| 18 | } |
| 19 | return static_cast<T>(x); |
| 20 | } |
Krzysztof Grobelny | e8fc575 | 2021-02-05 14:30:45 +0000 | [diff] [blame] | 21 | |
| 22 | template <class T> |
| 23 | inline std::underlying_type_t<T> toUnderlying(T value) |
| 24 | { |
| 25 | return static_cast<std::underlying_type_t<T>>(value); |
| 26 | } |
| 27 | |
| 28 | template <class T, size_t N> |
| 29 | inline 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 | |
| 42 | template <class T, size_t N> |
| 43 | inline 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, Jozef | d960e1f | 2021-01-08 09:25:59 +0100 | [diff] [blame] | 57 | } // namespace utils |