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

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

base: crash with an assert error if trying to access a read-only map
with a nonexistent key.

  • Property svn:keywords set to Id
File size: 2.3 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    /* 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
77private:
78    Array<uint32_t, K, V> m_array;
79};
80
81} /* namespace lol */
82
83#endif // __LOL_BASE_MAP_H__
84
Note: See TracBrowser for help on using the repository browser.