source: trunk/src/lol/core/map.h @ 2183

Last change on this file since 2183 was 2183, checked in by sam, 7 years ago

build: fix the WTFPL site URL in all code comments.

  • Property svn:keywords set to Id
File size: 2.3 KB
Line 
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://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_CORE_MAP_H__
18#define __LOL_CORE_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    /* 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        return V();
39    }
40
41    inline V & operator[] (K const &key)
42    {
43        /* Look for the hash in our table and return the value if found. */
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                    return m_array[i].m3;
49        /* If not found, insert a new value. */
50        m_array.Push(hash, key, V());
51        return m_array.Last().m3;
52    }
53
54    inline void Remove(K const &key)
55    {
56        uint32_t hash = ((Hash<K> const &)*this)(key);
57        for (int i = 0; i < m_array.Count(); ++i)
58            if (m_array[i].m1 == hash)
59                if (m_array[i].m2 == key)
60                {
61                    m_array.Remove(i);
62                    return;
63                }
64    }
65
66    inline bool HasKey(K const &key)
67    {
68        uint32_t hash = ((Hash<K> const &)*this)(key);
69        for (int i = 0; i < m_array.Count(); ++i)
70            if (m_array[i].m1 == hash)
71                if (m_array[i].m2 == key)
72                    return true;
73        return false;
74    }
75
76private:
77    Array<uint32_t, K, V> m_array;
78};
79
80} /* namespace lol */
81
82#endif // __LOL_CORE_MAP_H__
83
Note: See TracBrowser for help on using the repository browser.