1 /**
2 * Copyright (c) 2006-2011 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 	template<typename T, typename U, unsigned PEAK>
29 	class EnumMap
30 	{
31 	private:
32 
33 		struct Value
34 		{
35 			unsigned v;
36 			bool set;
ValueValue37 			Value() : set(false) {}
38 		};
39 
40 		Value values_t[PEAK];
41 		Value values_u[PEAK];
42 
43 	public:
44 
45 		struct Entry
46 		{
47 			T t;
48 			U u;
49 		};
50 
EnumMap(Entry * entries,unsigned size)51 		EnumMap(Entry * entries, unsigned size)
52 		{
53 			unsigned n = size/sizeof(Entry);
54 
55 			for(unsigned i = 0; i<n; ++i)
56 			{
57 				unsigned e_t = (unsigned)entries[i].t;
58 				unsigned e_u = (unsigned)entries[i].u;
59 
60 				if(e_t < PEAK)
61 				{
62 					values_u[e_t].v = e_u;
63 					values_u[e_t].set = true;
64 				}
65 				if(e_u < PEAK)
66 				{
67 					values_t[e_u].v = e_t;
68 					values_t[e_u].set = true;
69 				}
70 			}
71 		}
72 
find(T t,U & u)73 		bool find(T t, U & u)
74 		{
75 			if((unsigned)t < PEAK && values_u[(unsigned)t].set)
76 			{
77 				u = (U)values_u[(unsigned)t].v;
78 				return true;
79 			}
80 
81 			return false;
82 		}
83 
find(U u,T & t)84 		bool find(U u, T & t)
85 		{
86 			if((unsigned)u < PEAK && values_t[(unsigned)u].set)
87 			{
88 				t = (T)values_t[(unsigned)u].v;
89 				return true;
90 			}
91 
92 			return false;
93 		}
94 
95 	}; // EnumMap
96 
97 } // love
98 
99 #endif // LOVE_ENUM_MAP_H
100