Antares Simulator
Power System Simulator
Enum.hxx
1 /*
2  * Copyright 2007-2025, RTE (https://www.rte-france.com)
3  * See AUTHORS.txt
4  * SPDX-License-Identifier: MPL-2.0
5  * This file is part of Antares-Simulator,
6  * Adequacy and Performance assessment for interconnected energy networks.
7  *
8  * Antares_Simulator is free software: you can redistribute it and/or modify
9  * it under the terms of the Mozilla Public Licence 2.0 as published by
10  * the Mozilla Foundation, either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * Antares_Simulator is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * Mozilla Public Licence 2.0 for more details.
17  *
18  * You should have received a copy of the Mozilla Public Licence 2.0
19  * along with Antares_Simulator. If not, see <https://opensource.org/license/mpl-2-0/>.
20  */
21 
22 #ifndef ANTARES_DATA_ENUM_HXX
23 #define ANTARES_DATA_ENUM_HXX
24 
25 #include <algorithm>
26 #include <list>
27 #include <stdexcept>
28 
29 #include <antares/enums/class_name.h>
30 #include "antares/exception/AssertionError.hpp"
31 
32 namespace Antares::Data::Enum
33 {
34 template<typename E, typename>
35 E fromString(const std::string& name)
36 {
37  const auto& names = getNames<E>();
38  const auto& it = std::find(names.begin(), names.end(), name);
39  if (it == names.end())
40  {
41  throw AssertionError("Unexpected " + stdcxx::simpleClassName<E>() + " name " + name);
42  }
43 
44  return static_cast<E>(it - names.begin());
45 }
46 
47 template<typename E, typename>
48 std::string toString(const E& value)
49 {
50  auto index = static_cast<unsigned long>(value);
51  const auto& names = getNames<E>();
52  if (index >= names.size())
53  {
54  throw std::runtime_error("Unexpected " + stdcxx::simpleClassName<E>() + " value "
55  + std::to_string(index));
56  }
57  return *(names.begin() + index);
58 }
59 
60 template<typename E, typename>
61 std::list<E> enumList()
62 {
63  std::list<E> result;
64  const auto& names = getNames<E>();
65  for (auto name: names)
66  {
67  result.push_back(fromString<E>(name));
68  }
69 
70  return result;
71 }
72 
73 } // namespace Antares::Data::Enum
74 
75 #endif // ANTARES_DATA_ENUM_HXX