1 | // |
---|

2 | // Lol Engine |
---|

3 | // |
---|

4 | // Copyright: (c) 2010-2013 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://www.wtfpl.net/ for more details. |
---|

9 | // |
---|

10 | |
---|

11 | // |
---|

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

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

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

15 | // |
---|

16 | |
---|

17 | #if !defined __LOL_BASE_MAP_H__ |
---|

18 | #define __LOL_BASE_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 | /* I choose to make this inline because passing the key by reference |
---|

28 | * is usually suboptimal. */ |
---|

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

30 | { |
---|

31 | /* Look for the hash in our table and return the value. */ |
---|

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

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

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

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

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

37 | /* XXX: this in an error! */ |
---|

38 | ASSERT(0, "trying to read a non-existent key in map"); |
---|

39 | return V(); |
---|

40 | } |
---|

41 | |
---|

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

43 | { |
---|

44 | /* Look for the hash in our table and return the value if found. */ |
---|

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

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

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

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

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

50 | /* If not found, insert a new value. */ |
---|

51 | m_array.Push(hash, key, V()); |
---|

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

53 | } |
---|

54 | |
---|

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

56 | { |
---|

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

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

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

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

61 | { |
---|

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

63 | return; |
---|

64 | } |
---|

65 | } |
---|

66 | |
---|

67 | inline bool HasKey(K const &key) |
---|

68 | { |
---|

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

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

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

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

73 | return true; |
---|

74 | return false; |
---|

75 | } |
---|

76 | |
---|

77 | private: |
---|

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

79 | }; |
---|

80 | |
---|

81 | } /* namespace lol */ |
---|

82 | |
---|

83 | #endif // __LOL_BASE_MAP_H__ |
---|

84 | |
---|