EnumMap.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * Copyright (c) 2006-2025 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. #ifndef LOVE_ENUM_MAP_H
  21. #define LOVE_ENUM_MAP_H
  22. #include "Exception.h"
  23. namespace love
  24. {
  25. template<typename T, typename U, unsigned int PEAK>
  26. class EnumMap
  27. {
  28. public:
  29. struct Entry
  30. {
  31. T t;
  32. U u;
  33. };
  34. EnumMap(const Entry *entries, unsigned int size)
  35. {
  36. unsigned int n = size / sizeof(Entry);
  37. for (unsigned int i = 0; i < n; ++i)
  38. {
  39. unsigned int e_t = (unsigned int) entries[i].t;
  40. unsigned int e_u = (unsigned int) entries[i].u;
  41. if (e_t < PEAK)
  42. {
  43. values_u[e_t].v = e_u;
  44. values_u[e_t].set = true;
  45. }
  46. if (e_u < PEAK)
  47. {
  48. values_t[e_u].v = e_t;
  49. values_t[e_u].set = true;
  50. }
  51. }
  52. }
  53. bool find(T t, U &u)
  54. {
  55. if ((unsigned int) t < PEAK && values_u[(unsigned int) t].set)
  56. {
  57. u = (U) values_u[(unsigned int) t].v;
  58. return true;
  59. }
  60. return false;
  61. }
  62. bool find(U u, T &t)
  63. {
  64. if ((unsigned int) u < PEAK && values_t[(unsigned int) u].set)
  65. {
  66. t = (T) values_t[(unsigned int) u].v;
  67. return true;
  68. }
  69. return false;
  70. }
  71. private:
  72. struct Value
  73. {
  74. unsigned v;
  75. bool set;
  76. Value() : set(false) {}
  77. };
  78. Value values_t[PEAK];
  79. Value values_u[PEAK];
  80. }; // EnumMap
  81. } // love
  82. #endif // LOVE_ENUM_MAP_H