| 1 | /** |
| 2 | * Copyright (c) 2006-2023 LOVE Development Team |
| 3 | * |
| 4 | * This software is provided 'as-is', without any express or implied |
| 5 | * warranty. In no event will the authors be held liable for any damages |
| 6 | * arising from the use of this software. |
| 7 | * |
| 8 | * Permission is granted to anyone to use this software for any purpose, |
| 9 | * including commercial applications, and to alter it and redistribute it |
| 10 | * freely, subject to the following restrictions: |
| 11 | * |
| 12 | * 1. The origin of this software must not be misrepresented; you must not |
| 13 | * claim that you wrote the original software. If you use this software |
| 14 | * in a product, an acknowledgment in the product documentation would be |
| 15 | * appreciated but is not required. |
| 16 | * 2. Altered source versions must be plainly marked as such, and must not be |
| 17 | * misrepresented as being the original software. |
| 18 | * 3. This notice may not be removed or altered from any source distribution. |
| 19 | **/ |
| 20 | |
| 21 | #ifndef LOVE_ENUM_MAP_H |
| 22 | #define LOVE_ENUM_MAP_H |
| 23 | |
| 24 | #include "Exception.h" |
| 25 | |
| 26 | namespace love |
| 27 | { |
| 28 | |
| 29 | template<typename T, typename U, unsigned int PEAK> |
| 30 | class EnumMap |
| 31 | { |
| 32 | public: |
| 33 | |
| 34 | struct Entry |
| 35 | { |
| 36 | T t; |
| 37 | U u; |
| 38 | }; |
| 39 | |
| 40 | EnumMap(const Entry *entries, unsigned int size) |
| 41 | { |
| 42 | unsigned int n = size / sizeof(Entry); |
| 43 | |
| 44 | for (unsigned int i = 0; i < n; ++i) |
| 45 | { |
| 46 | unsigned int e_t = (unsigned int) entries[i].t; |
| 47 | unsigned int e_u = (unsigned int) entries[i].u; |
| 48 | |
| 49 | if (e_t < PEAK) |
| 50 | { |
| 51 | values_u[e_t].v = e_u; |
| 52 | values_u[e_t].set = true; |
| 53 | } |
| 54 | if (e_u < PEAK) |
| 55 | { |
| 56 | values_t[e_u].v = e_t; |
| 57 | values_t[e_u].set = true; |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | bool find(T t, U &u) |
| 63 | { |
| 64 | if ((unsigned int) t < PEAK && values_u[(unsigned int) t].set) |
| 65 | { |
| 66 | u = (U) values_u[(unsigned int) t].v; |
| 67 | return true; |
| 68 | } |
| 69 | |
| 70 | return false; |
| 71 | } |
| 72 | |
| 73 | bool find(U u, T &t) |
| 74 | { |
| 75 | if ((unsigned int) u < PEAK && values_t[(unsigned int) u].set) |
| 76 | { |
| 77 | t = (T) values_t[(unsigned int) u].v; |
| 78 | return true; |
| 79 | } |
| 80 | |
| 81 | return false; |
| 82 | } |
| 83 | |
| 84 | private: |
| 85 | |
| 86 | struct Value |
| 87 | { |
| 88 | unsigned v; |
| 89 | bool set; |
| 90 | Value() : set(false) {} |
| 91 | }; |
| 92 | |
| 93 | Value values_t[PEAK]; |
| 94 | Value values_u[PEAK]; |
| 95 | |
| 96 | }; // EnumMap |
| 97 | |
| 98 | } // love |
| 99 | |
| 100 | #endif // LOVE_ENUM_MAP_H |
| 101 | |