1 | // |
---|

2 | // Lol Engine |
---|

3 | // |
---|

4 | // Copyright: (c) 2010-2012 Sam Hocevar <sam@hocevar.net> |
---|

5 | // This program is free software; you can redistribute it and/or |
---|

6 | // modify it under the terms of the Do What The Fuck You Want To |
---|

7 | // Public License, Version 2, as published by Sam Hocevar. See |
---|

8 | // http://sam.zoy.org/projects/COPYING.WTFPL for more details. |
---|

9 | // |
---|

10 | |
---|

11 | // |
---|

12 | // The Map class |
---|

13 | // ------------- |
---|

14 | // A very simple Map class. |
---|

15 | // |
---|

16 | |
---|

17 | #if !defined __LOL_CORE_MAP_H__ |
---|

18 | #define __LOL_CORE_MAP_H__ |
---|

19 | |
---|

20 | namespace lol |
---|

21 | { |
---|

22 | |
---|

23 | /* A stupidly linear map for now */ |
---|

24 | template<typename K, typename V> class Map : protected Hash<K> |
---|

25 | { |
---|

26 | public: |
---|

27 | inline V const& operator[] (K const &key) const |
---|

28 | { |
---|

29 | uint32_t hash = ((Hash<K> const &)*this)(key); |
---|

30 | for (int i = 0; i < m_array.Count(); ++i) |
---|

31 | if (m_array[i].m1 == hash) |
---|

32 | if (m_array[i].m2 == key) |
---|

33 | return m_array[i].m3; |
---|

34 | return V(); |
---|

35 | } |
---|

36 | |
---|

37 | inline V & operator[] (K const &key) |
---|

38 | { |
---|

39 | return const_cast<V &>((const_cast<Map<K,V> const &>(*this))[key]); |
---|

40 | } |
---|

41 | |
---|

42 | inline V & Set(K const &key, V const &val) |
---|

43 | { |
---|

44 | uint32_t hash = ((Hash<K> const &)*this)(key); |
---|

45 | for (int i = 0; i < m_array.Count(); ++i) |
---|

46 | if (m_array[i].m1 == hash) |
---|

47 | if (m_array[i].m2 == key) |
---|

48 | { |
---|

49 | m_array[i].m3.~V(); |
---|

50 | return m_array[i].m3 = val; |
---|

51 | } |
---|

52 | |
---|

53 | m_array.Push(hash, key, val); |
---|

54 | return m_array.Last().m3; |
---|

55 | } |
---|

56 | |
---|

57 | inline void Remove(K const &key) |
---|

58 | { |
---|

59 | uint32_t hash = ((Hash<K> const &)*this)(key); |
---|

60 | for (int i = 0; i < m_array.Count(); ++i) |
---|

61 | if (m_array[i].m1 == hash) |
---|

62 | if (m_array[i].m2 == key) |
---|

63 | { |
---|

64 | m_array.Remove(i); |
---|

65 | return; |
---|

66 | } |
---|

67 | } |
---|

68 | |
---|

69 | private: |
---|

70 | Array<uint32_t, K, V> m_array; |
---|

71 | }; |
---|

72 | |
---|

73 | } /* namespace lol */ |
---|

74 | |
---|

75 | #endif // __LOL_CORE_MAP_H__ |
---|

76 | |
---|