| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629 |
- //
- // Copyright (c) 2008-2014 the Urho3D project.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- //
- #pragma once
- #include "HashBase.h"
- #include "Pair.h"
- #include "Sort.h"
- #include "Vector.h"
- #include <cassert>
- namespace Urho3D
- {
- /// Hash map template class.
- template <class T, class U> class HashMap : public HashBase
- {
- public:
- /// Hash map key-value pair with const key.
- class KeyValue
- {
- public:
- /// Construct with default key.
- KeyValue() :
- first_(T())
- {
- }
-
- /// Construct with key and value.
- KeyValue(const T& first, const U& second) :
- first_(first),
- second_(second)
- {
- }
-
- /// Test for equality with another pair.
- bool operator == (const KeyValue& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
- /// Test for inequality with another pair.
- bool operator != (const KeyValue& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
-
- /// Key.
- const T first_;
- /// Value.
- U second_;
- };
-
- /// Hash map node.
- struct Node : public HashNodeBase
- {
- /// Construct undefined.
- Node()
- {
- }
-
- /// Construct with key and value.
- Node(const T& key, const U& value) :
- pair_(key, value)
- {
- }
-
- /// Key-value pair.
- KeyValue pair_;
-
- /// Return next node.
- Node* Next() const { return static_cast<Node*>(next_); }
- /// Return previous node.
- Node* Prev() const { return static_cast<Node*>(prev_); }
- /// Return next node in the bucket.
- Node* Down() const { return static_cast<Node*>(down_); }
- };
-
- /// Hash map node iterator.
- struct Iterator : public HashIteratorBase
- {
- /// Construct.
- Iterator()
- {
- }
-
- /// Construct with a node pointer.
- Iterator(Node* ptr) :
- HashIteratorBase(ptr)
- {
- }
-
- /// Preincrement the pointer.
- Iterator& operator ++ () { GotoNext(); return *this; }
- /// Postincrement the pointer.
- Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
- /// Predecrement the pointer.
- Iterator& operator -- () { GotoPrev(); return *this; }
- /// Postdecrement the pointer.
- Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
-
- /// Point to the pair.
- KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
- /// Dereference the pair.
- KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
- };
-
- /// Hash map node const iterator.
- struct ConstIterator : public HashIteratorBase
- {
- /// Construct.
- ConstIterator()
- {
- }
-
- /// Construct with a node pointer.
- ConstIterator(Node* ptr) :
- HashIteratorBase(ptr)
- {
- }
-
- /// Construct from a non-const iterator.
- ConstIterator(const Iterator& rhs) :
- HashIteratorBase(rhs.ptr_)
- {
- }
-
- /// Assign from a non-const iterator.
- ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
- /// Preincrement the pointer.
- ConstIterator& operator ++ () { GotoNext(); return *this; }
- /// Postincrement the pointer.
- ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
- /// Predecrement the pointer.
- ConstIterator& operator -- () { GotoPrev(); return *this; }
- /// Postdecrement the pointer.
- ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
-
- /// Point to the pair.
- const KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
- /// Dereference the pair.
- const KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
- };
-
- /// Construct empty.
- HashMap()
- {
- // Reserve the tail node
- allocator_ = AllocatorInitialize(sizeof(Node));
- head_ = tail_ = ReserveNode();
- }
-
- /// Construct from another hash map.
- HashMap(const HashMap<T, U>& map)
- {
- // Reserve the tail node + initial capacity according to the map's size
- allocator_ = AllocatorInitialize(sizeof(Node), map.Size() + 1);
- head_ = tail_ = ReserveNode();
- *this = map;
- }
-
- /// Destruct.
- ~HashMap()
- {
- Clear();
- FreeNode(Tail());
- AllocatorUninitialize(allocator_);
- }
-
- /// Assign a hash map.
- HashMap& operator = (const HashMap<T, U>& rhs)
- {
- Clear();
- Insert(rhs);
- return *this;
- }
-
- /// Add-assign a pair.
- HashMap& operator += (const Pair<T, U>& rhs)
- {
- Insert(rhs);
- return *this;
- }
-
- /// Add-assign a hash map.
- HashMap& operator += (const HashMap<T, U>& rhs)
- {
- Insert(rhs);
- return *this;
- }
-
- /// Test for equality with another hash map.
- bool operator == (const HashMap<T, U>& rhs) const
- {
- if (rhs.Size() != Size())
- return false;
-
- ConstIterator i = Begin();
- while (i != End())
- {
- ConstIterator j = rhs.Find(i->first_);
- if (j == rhs.End() || j->second_ != i->second_)
- return false;
- ++i;
- }
-
- return true;
- }
-
- /// Test for inequality with another hash map.
- bool operator != (const HashMap<T, U>& rhs) const
- {
- if (rhs.Size() != Size())
- return true;
-
- ConstIterator i = Begin();
- while (i != End())
- {
- ConstIterator j = rhs.Find(i->first_);
- if (j == rhs.End() || j->second_ != i->second_)
- return true;
- ++i;
- }
-
- return false;
- }
-
- /// Index the map. Create a new pair if key not found.
- U& operator [] (const T& key)
- {
- if (!ptrs_)
- return InsertNode(key, U(), false)->pair_.second_;
-
- unsigned hashKey = Hash(key);
-
- Node* node = FindNode(key, hashKey);
- if (node)
- return node->pair_.second_;
- else
- return InsertNode(key, U(), false)->pair_.second_;
- }
-
- /// Insert a pair. Return an iterator to it.
- Iterator Insert(const Pair<T, U>& pair)
- {
- return Iterator(InsertNode(pair.first_, pair.second_));
- }
-
- /// Insert a map.
- void Insert(const HashMap<T, U>& map)
- {
- ConstIterator it = map.Begin();
- ConstIterator end = map.End();
- while (it != end)
- {
- InsertNode(it->first_, it->second_);
- ++it;
- }
- }
-
- /// Insert a pair by iterator. Return iterator to the value.
- Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(it->first_, it->second_)); }
-
- /// Insert a range by iterators.
- void Insert(const ConstIterator& start, const ConstIterator& end)
- {
- ConstIterator it = start;
- while (it != end)
- InsertNode(*it++);
- }
-
- /// Erase a pair by key. Return true if was found.
- bool Erase(const T& key)
- {
- if (!ptrs_)
- return false;
-
- unsigned hashKey = Hash(key);
-
- Node* previous;
- Node* node = FindNode(key, hashKey, previous);
- if (!node)
- return false;
-
- if (previous)
- previous->down_ = node->down_;
- else
- Ptrs()[hashKey] = node->down_;
-
- EraseNode(node);
- return true;
- }
-
- /// Erase a pair by iterator. Return iterator to the next pair.
- Iterator Erase(const Iterator& it)
- {
- if (!ptrs_ || !it.ptr_)
- return End();
-
- Node* node = static_cast<Node*>(it.ptr_);
- Node* next = node->Next();
-
- unsigned hashKey = Hash(node->pair_.first_);
-
- Node* previous = 0;
- Node* current = static_cast<Node*>(Ptrs()[hashKey]);
- while (current && current != node)
- {
- previous = current;
- current = current->Down();
- }
-
- assert(current == node);
-
- if (previous)
- previous->down_ = node->down_;
- else
- Ptrs()[hashKey] = node->down_;
-
- EraseNode(node);
- return Iterator(next);
- }
-
- /// Clear the map.
- void Clear()
- {
- if (Size())
- {
- for (Iterator i = Begin(); i != End(); )
- {
- FreeNode(static_cast<Node*>(i++.ptr_));
- i.ptr_->prev_ = 0;
- }
-
- head_ = tail_;
- SetSize(0);
- }
-
- ResetPtrs();
- }
-
- /// Sort pairs. After sorting the map can be iterated in order until new elements are inserted.
- void Sort()
- {
- unsigned numKeys = Size();
- if (!numKeys)
- return;
-
- Node** ptrs = new Node*[numKeys];
- Node* ptr = Head();
-
- for (unsigned i = 0; i < numKeys; ++i)
- {
- ptrs[i] = ptr;
- ptr = ptr->Next();
- }
-
- Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
-
- head_ = ptrs[0];
- ptrs[0]->prev_ = 0;
- for (unsigned i = 1; i < numKeys; ++i)
- {
- ptrs[i - 1]->next_ = ptrs[i];
- ptrs[i]->prev_ = ptrs[i - 1];
- }
- ptrs[numKeys - 1]->next_ = tail_;
- tail_->prev_ = ptrs[numKeys - 1];
-
- delete[] ptrs;
- }
-
- /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
- bool Rehash(unsigned numBuckets)
- {
- if (numBuckets == NumBuckets())
- return true;
- if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
- return false;
-
- // Check for being power of two
- unsigned check = numBuckets;
- while (!(check & 1))
- check >>= 1;
- if (check != 1)
- return false;
-
- AllocateBuckets(Size(), numBuckets);
- Rehash();
- return true;
- }
-
- /// Return iterator to the pair with key, or end iterator if not found.
- Iterator Find(const T& key)
- {
- if (!ptrs_)
- return End();
-
- unsigned hashKey = Hash(key);
- Node* node = FindNode(key, hashKey);
- if (node)
- return Iterator(node);
- else
- return End();
- }
-
- /// Return const iterator to the pair with key, or end iterator if not found.
- ConstIterator Find(const T& key) const
- {
- if (!ptrs_)
- return End();
-
- unsigned hashKey = Hash(key);
- Node* node = FindNode(key, hashKey);
- if (node)
- return ConstIterator(node);
- else
- return End();
- }
-
- /// Return whether contains a pair with key.
- bool Contains(const T& key) const
- {
- if (!ptrs_)
- return false;
-
- unsigned hashKey = Hash(key);
- return FindNode(key, hashKey) != 0;
- }
-
- /// Return all the keys.
- Vector<T> Keys() const
- {
- Vector<T> result;
- result.Reserve(Size());
- for (ConstIterator i = Begin(); i != End(); ++i)
- result.Push(i->first_);
- return result;
- }
- /// Return iterator to the beginning.
- Iterator Begin() { return Iterator(Head()); }
- /// Return iterator to the beginning.
- ConstIterator Begin() const { return ConstIterator(Head()); }
- /// Return iterator to the end.
- Iterator End() { return Iterator(Tail()); }
- /// Return iterator to the end.
- ConstIterator End() const { return ConstIterator(Tail()); }
- /// Return first key.
- const T& Front() const { return *Begin(); }
- /// Return last key.
- const T& Back() const { return *(--End()); }
-
- private:
- /// Return the head node.
- Node* Head() const { return static_cast<Node*>(head_); }
- /// Return the tail node.
- Node* Tail() const { return static_cast<Node*>(tail_); }
-
- /// Find a node from the buckets. Do not call if the buckets have not been allocated.
- Node* FindNode(const T& key, unsigned hashKey) const
- {
- Node* node = static_cast<Node*>(Ptrs()[hashKey]);
- while (node)
- {
- if (node->pair_.first_ == key)
- return node;
- node = node->Down();
- }
-
- return 0;
- }
-
- /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
- Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
- {
- previous = 0;
-
- Node* node = static_cast<Node*>(Ptrs()[hashKey]);
- while (node)
- {
- if (node->pair_.first_ == key)
- return node;
- previous = node;
- node = node->Down();
- }
-
- return 0;
- }
-
- /// Insert a key and value and return either the new or existing node.
- Node* InsertNode(const T& key, const U& value, bool findExisting = true)
- {
- // If no pointers yet, allocate with minimum bucket count
- if (!ptrs_)
- {
- AllocateBuckets(Size(), MIN_BUCKETS);
- Rehash();
- }
-
- unsigned hashKey = Hash(key);
-
- if (findExisting)
- {
- // If exists, just change the value
- Node* existing = FindNode(key, hashKey);
- if (existing)
- {
- existing->pair_.second_ = value;
- return existing;
- }
- }
-
- Node* newNode = InsertNode(Tail(), key, value);
- newNode->down_ = Ptrs()[hashKey];
- Ptrs()[hashKey] = newNode;
-
- // Rehash if the maximum load factor has been exceeded
- if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
- {
- AllocateBuckets(Size(), NumBuckets() << 1);
- Rehash();
- }
-
- return newNode;
- }
-
- /// Insert a node into the list. Return the new node.
- Node* InsertNode(Node* dest, const T& key, const U& value)
- {
- if (!dest)
- return 0;
-
- Node* newNode = ReserveNode(key, value);
- Node* prev = dest->Prev();
- newNode->next_ = dest;
- newNode->prev_ = prev;
- if (prev)
- prev->next_ = newNode;
- dest->prev_ = newNode;
-
- // Reassign the head node if necessary
- if (dest == Head())
- head_ = newNode;
-
- SetSize(Size() + 1);
-
- return newNode;
- }
-
- /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
- Node* EraseNode(Node* node)
- {
- // The tail node can not be removed
- if (!node || node == tail_)
- return Tail();
-
- Node* prev = node->Prev();
- Node* next = node->Next();
- if (prev)
- prev->next_ = next;
- next->prev_ = prev;
-
- // Reassign the head node if necessary
- if (node == Head())
- head_ = next;
-
- FreeNode(node);
- SetSize(Size() - 1);
-
- return next;
- }
-
- /// Reserve a node.
- Node* ReserveNode()
- {
- Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
- new(newNode) Node();
- return newNode;
- }
-
- /// Reserve a node with specified key and value.
- Node* ReserveNode(const T& key, const U& value)
- {
- Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
- new(newNode) Node(key, value);
- return newNode;
- }
-
- /// Free a node.
- void FreeNode(Node* node)
- {
- (node)->~Node();
- AllocatorFree(allocator_, node);
- }
-
- /// Rehash the buckets.
- void Rehash()
- {
- for (Iterator i = Begin(); i != End(); ++i)
- {
- Node* node = static_cast<Node*>(i.ptr_);
- unsigned hashKey = Hash(i->first_);
- node->down_ = Ptrs()[hashKey];
- Ptrs()[hashKey] = node;
- }
- }
-
- /// Compare two nodes.
- static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->pair_.first_ < rhs->pair_.first_; }
-
- /// Compute a hash based on the key and the bucket size
- unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
- };
- }
|