Browse Source

map: re-using avl_tree in map and adding tests for string comparisons.

undefined
Guillaume Bittoun Sam Hocevar <sam@hocevar.net> 10 years ago
parent
commit
8c44cb4f1b
2 changed files with 3 additions and 101 deletions
  1. +0
    -101
      src/lol/base/map.h
  2. +3
    -0
      src/t/base/string.cpp

+ 0
- 101
src/lol/base/map.h View File

@@ -22,7 +22,6 @@
namespace lol
{

#if USING_AVL
/* A stupidly linear map for now. */
template<typename K, typename V> class map : protected hash<K>
{
@@ -115,106 +114,6 @@ private:

avl_tree<K, V> m_tree;
};
#else
/* A stupidly linear map for now. */
template<typename K, typename V> class map : protected hash<K>
{
public:
/* If E is different from K, hash<K> must implement operator()(E const&)
* and an equality operator between K and E must exist in order to use
* this method. */

/* I choose to make this inline because passing the key by reference
* is usually suboptimal. */
template <typename E>
inline V const& operator[] (E const &key) const
{
/* Look for the hash in our table and return the value. */
ptrdiff_t i = FindIndex(key);
ASSERT(i >= 0, "trying to read a nonexistent key in map");
return m_array[i].m3;
}

template <typename E>
inline V & operator[] (E const &key)
{
/* Look for the hash in our table and return the value if found. */
uint32_t hashed = ((hash<K> const &)*this)(key);
ptrdiff_t i = FindIndex(key, hashed);
if (i >= 0)
return m_array[i].m3;

/* If not found, insert a new value. */
m_array.Push(hashed, key, V());
return m_array.Last().m3;
}

template <typename E>
inline void Remove(E const &key)
{
ptrdiff_t i = FindIndex(key);
if (i >= 0)
m_array.Remove(i);
}

template <typename E>
inline bool HasKey(E const &key)
{
return FindIndex(key) >= 0;
}

template <typename E>
inline bool TryGetValue(E const &key, V& value)
{
ptrdiff_t i = FindIndex(key);
if (i >= 0)
{
value = m_array[i].m3;
return true;
}

return false;
}

array<K> Keys() const
{
array<K> ret;
for (auto it : m_array)
ret.Push(it.m2);
return ret;
}

inline ptrdiff_t Count() const
{
return m_array.Count();
}

inline void Empty()
{
m_array.Empty();
}

private:
template <typename E>
inline ptrdiff_t FindIndex(E const &key, uint32_t hashed)
{
for (ptrdiff_t i = 0; i < m_array.Count(); ++i)
if (m_array[i].m1 == hashed)
if (m_array[i].m2 == key)
return i;
return -1;
}

template <typename E>
inline ptrdiff_t FindIndex(E const &key)
{
uint32_t hashed = ((hash<K> const &)*this)(key);
return FindIndex(key, hashed);
}

array<uint32_t, K, V> m_array;
};
#endif //USING_AVL

} /* namespace lol */


+ 3
- 0
src/t/base/string.cpp View File

@@ -233,10 +233,13 @@ lolunit_declare_fixture(StringTest)
String s1 = "lolilol";
String s2 = s1;
String s3 = "trololol";
String s4 = "lolilololol";

lolunit_assert(!(s1 < s2));
lolunit_assert(!(s2 < s1));
lolunit_assert(s1 < s3);
lolunit_assert(s1 < s4);
lolunit_assert(!(s4 < s1));
}
};



Loading…
Cancel
Save