diff -r 000000000000 -r 6474c204b198 xpcom/glue/nsClassHashtable.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/xpcom/glue/nsClassHashtable.h Wed Dec 31 06:09:35 2014 +0100 @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef nsClassHashtable_h__ +#define nsClassHashtable_h__ + +#include "nsBaseHashtable.h" +#include "nsHashKeys.h" +#include "nsAutoPtr.h" + +/** + * templated hashtable class maps keys to C++ object pointers. + * See nsBaseHashtable for complete declaration. + * @param KeyClass a wrapper-class for the hashtable key, see nsHashKeys.h + * for a complete specification. + * @param Class the class-type being wrapped + * @see nsInterfaceHashtable, nsClassHashtable + */ +template +class nsClassHashtable : + public nsBaseHashtable< KeyClass, nsAutoPtr, T* > +{ +public: + typedef typename KeyClass::KeyType KeyType; + typedef T* UserDataType; + typedef nsBaseHashtable< KeyClass, nsAutoPtr, T* > base_type; + + nsClassHashtable() + { + } + explicit nsClassHashtable(uint32_t aInitSize) + : nsBaseHashtable,T*>(aInitSize) + { + } + + /** + * @copydoc nsBaseHashtable::Get + * @param pData if the key doesn't exist, pData will be set to nullptr. + */ + bool Get(KeyType aKey, UserDataType* pData) const; + + /** + * @copydoc nsBaseHashtable::Get + * @returns nullptr if the key is not present. + */ + UserDataType Get(KeyType aKey) const; + + /** + * Remove the entry for the given key from the hashtable and return it in + * aOut. If the key is not in the hashtable, aOut's pointer is set to + * nullptr. + * + * Normally, an entry is deleted when it's removed from an nsClassHashtable, + * but this function transfers ownership of the entry back to the caller + * through aOut -- the entry will be deleted when aOut goes out of scope. + * + * @param aKey the key to get and remove from the hashtable + */ + void RemoveAndForget(KeyType aKey, nsAutoPtr &aOut); +}; + +// +// nsClassHashtable definitions +// + +template +bool +nsClassHashtable::Get(KeyType aKey, T** retVal) const +{ + typename base_type::EntryType* ent = this->GetEntry(aKey); + + if (ent) + { + if (retVal) + *retVal = ent->mData; + + return true; + } + + if (retVal) + *retVal = nullptr; + + return false; +} + +template +T* +nsClassHashtable::Get(KeyType aKey) const +{ + typename base_type::EntryType* ent = this->GetEntry(aKey); + + if (!ent) + return nullptr; + + return ent->mData; +} + +template +void +nsClassHashtable::RemoveAndForget(KeyType aKey, nsAutoPtr &aOut) +{ + aOut = nullptr; + nsAutoPtr ptr; + + typename base_type::EntryType *ent = this->GetEntry(aKey); + if (!ent) + return; + + // Transfer ownership from ent->mData into aOut. + aOut = ent->mData; + + this->Remove(aKey); +} + +#endif // nsClassHashtable_h__