source: trunk/src/lol/base/map.h @ 2807

Last change on this file since 2807 was 2807, checked in by sam, 8 years ago

base: simplify the Map code.

  • Property svn:keywords set to Id
File size: 2.5 KB
Line 
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
20namespace lol
21{
22
23/* A stupidly linear map for now. */
24template<typename K, typename V> class Map : protected Hash<K>
25{
26public:
27    /* If E is different from K, Hash<K> must implement operator()(E const&)
28     * and an equality operator between K and E must exist in order to use
29     * this method. */
30
31    /* I choose to make this inline because passing the key by reference
32     * is usually suboptimal. */
33    template <typename E>
34    inline V const& operator[] (E const &key) const
35    {
36        /* Look for the hash in our table and return the value. */
37        int i = FindIndex(key);
38        ASSERT(i >= 0, "trying to read a nonexistent key in map");
39        return m_array[i].m3;
40    }
41
42    template <typename E>
43    inline V & operator[] (E const &key)
44    {
45        /* Look for the hash in our table and return the value if found. */
46        int i = FindIndex(key);
47        if (i >= 0)
48            return m_array[i].m3;
49
50        /* If not found, insert a new value. */
51        m_array.Push(hash, key, V());
52        return m_array.Last().m3;
53    }
54
55    template <typename E>
56    inline void Remove(E const &key)
57    {
58        int i = FindIndex(key);
59        if (i >= 0)
60            m_array.Remove(i);
61    }
62
63    template <typename E>
64    inline bool HasKey(E const &key)
65    {
66        return FindIndex(key) >= 0;
67    }
68
69    template <typename E>
70    inline bool TryGetValue(E const &key, V& value)
71    {
72        int i = FindIndex(key);
73        if (i >= 0)
74        {
75            value = m_array[i].m3;
76            return true;
77        }
78
79        return false;
80    }
81
82    inline int Count() const
83    {
84        return m_array.Count();
85    }
86
87private:
88    template <typename E>
89    int FindIndex(E const &key)
90    {
91        uint32_t hash = ((Hash<K> const &)*this)(key);
92        for (int i = 0; i < m_array.Count(); ++i)
93            if (m_array[i].m1 == hash)
94                if (m_array[i].m2 == key)
95                    return i;
96        return -1;
97    }
98
99    Array<uint32_t, K, V> m_array;
100};
101
102} /* namespace lol */
103
104#endif // __LOL_BASE_MAP_H__
105
Note: See TracBrowser for help on using the repository browser.