SVGAttrTearoffTable.h (2803B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef DOM_SVG_SVGATTRTEAROFFTABLE_H_ 8 #define DOM_SVG_SVGATTRTEAROFFTABLE_H_ 9 10 #include "mozilla/DebugOnly.h" 11 #include "mozilla/StaticPtr.h" 12 #include "nsDebug.h" 13 #include "nsHashKeys.h" 14 #include "nsTHashMap.h" 15 16 namespace mozilla { 17 18 /** 19 * Global hashmap to associate internal SVG data types (e.g. SVGAnimatedLength) 20 * with DOM tear-off objects (e.g. DOMSVGLength). This allows us to always 21 * return the same object for subsequent requests for DOM objects. 22 * 23 * We don't keep an owning reference to the tear-off objects so they are 24 * responsible for removing themselves from this table when they die. 25 */ 26 template <class SimpleType, class TearoffType> 27 class SVGAttrTearoffTable { 28 public: 29 #ifdef DEBUG 30 ~SVGAttrTearoffTable() { 31 NS_ASSERTION(!mTable, "Tear-off objects remain in hashtable at shutdown."); 32 } 33 #endif 34 35 TearoffType* GetTearoff(SimpleType* aSimple); 36 37 void AddTearoff(SimpleType* aSimple, TearoffType* aTearoff); 38 39 void RemoveTearoff(SimpleType* aSimple); 40 41 private: 42 using SimpleTypePtrKey = nsPtrHashKey<SimpleType>; 43 using TearoffTable = nsTHashMap<SimpleTypePtrKey, TearoffType*>; 44 45 StaticAutoPtr<TearoffTable> mTable; 46 }; 47 48 template <class SimpleType, class TearoffType> 49 TearoffType* SVGAttrTearoffTable<SimpleType, TearoffType>::GetTearoff( 50 SimpleType* aSimple) { 51 if (!mTable) { 52 return nullptr; 53 } 54 55 TearoffType* tearoff = nullptr; 56 57 DebugOnly<bool> found = mTable->Get(aSimple, &tearoff); 58 MOZ_ASSERT(!found || tearoff, 59 "null pointer stored in attribute tear-off map"); 60 61 return tearoff; 62 } 63 64 template <class SimpleType, class TearoffType> 65 void SVGAttrTearoffTable<SimpleType, TearoffType>::AddTearoff( 66 SimpleType* aSimple, TearoffType* aTearoff) { 67 if (!mTable) { 68 mTable = new TearoffTable(); 69 } 70 71 // We shouldn't be adding a tear-off if there already is one. If that happens, 72 // something is wrong. 73 if (mTable->Get(aSimple, nullptr)) { 74 MOZ_ASSERT(false, "There is already a tear-off for this object."); 75 return; 76 } 77 78 mTable->InsertOrUpdate(aSimple, aTearoff); 79 } 80 81 template <class SimpleType, class TearoffType> 82 void SVGAttrTearoffTable<SimpleType, TearoffType>::RemoveTearoff( 83 SimpleType* aSimple) { 84 if (!mTable) { 85 // Perhaps something happened in between creating the SimpleType object and 86 // registering it 87 return; 88 } 89 90 mTable->Remove(aSimple); 91 if (mTable->Count() == 0) { 92 mTable = nullptr; 93 } 94 } 95 96 } // namespace mozilla 97 98 #endif // DOM_SVG_SVGATTRTEAROFFTABLE_H_