OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #ifndef NthIndexCache_h |
| 6 #define NthIndexCache_h |
| 7 |
| 8 #include "core/dom/Element.h" |
| 9 #include "core/dom/ElementTraversal.h" |
| 10 #include "platform/heap/Handle.h" |
| 11 #include "wtf/HashMap.h" |
| 12 #include "wtf/OwnPtr.h" |
| 13 #include "wtf/RefPtr.h" |
| 14 |
| 15 namespace blink { |
| 16 |
| 17 class Document; |
| 18 |
| 19 class NthIndexCache final { |
| 20 STACK_ALLOCATED(); |
| 21 WTF_MAKE_NONCOPYABLE(NthIndexCache); |
| 22 public: |
| 23 explicit NthIndexCache(Document&); |
| 24 ~NthIndexCache(); |
| 25 |
| 26 inline unsigned nthChildIndex(Element&); |
| 27 inline unsigned nthLastChildIndex(Element&); |
| 28 |
| 29 private: |
| 30 class NthIndexData final : public NoBaseWillBeGarbageCollected<NthIndexData>
{ |
| 31 WTF_MAKE_NONCOPYABLE(NthIndexData); |
| 32 DECLARE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(NthIndexData); |
| 33 public: |
| 34 NthIndexData() { } |
| 35 |
| 36 inline unsigned nthIndex(Element&); |
| 37 inline unsigned nthLastIndex(Element&); |
| 38 |
| 39 unsigned cacheNthIndices(Element&); |
| 40 |
| 41 WillBeHeapHashMap<RawPtrWillBeMember<Element>, unsigned> m_elementIndexM
ap; |
| 42 unsigned m_count = 0; |
| 43 |
| 44 DECLARE_TRACE(); |
| 45 }; |
| 46 |
| 47 NthIndexData& ensureNthIndexDataFor(Node&); |
| 48 inline unsigned nthIndex(Element&); |
| 49 |
| 50 using ParentMap = WillBeHeapHashMap<RefPtrWillBeMember<Node>, OwnPtrWillBeMe
mber<NthIndexData>>; |
| 51 |
| 52 OwnPtrWillBeMember<ParentMap> m_parentMap; |
| 53 RawPtrWillBeMember<Document> m_document; |
| 54 uint64_t m_domTreeVersion; |
| 55 }; |
| 56 |
| 57 inline unsigned NthIndexCache::NthIndexData::nthIndex(Element& element) |
| 58 { |
| 59 if (!m_count) |
| 60 return cacheNthIndices(element); |
| 61 |
| 62 unsigned index = 0; |
| 63 for (Element* sibling = &element; sibling; sibling = ElementTraversal::previ
ousSibling(*sibling), index++) { |
| 64 auto it = m_elementIndexMap.find(sibling); |
| 65 if (it != m_elementIndexMap.end()) |
| 66 return it->value + index; |
| 67 } |
| 68 return index; |
| 69 } |
| 70 |
| 71 inline unsigned NthIndexCache::NthIndexData::nthLastIndex(Element& element) |
| 72 { |
| 73 unsigned index = nthIndex(element); |
| 74 return m_count - index + 1; |
| 75 } |
| 76 |
| 77 inline unsigned NthIndexCache::nthChildIndex(Element& element) |
| 78 { |
| 79 ASSERT(element.parentNode()); |
| 80 return ensureNthIndexDataFor(*element.parentNode()).nthIndex(element); |
| 81 } |
| 82 |
| 83 inline unsigned NthIndexCache::nthLastChildIndex(Element& element) |
| 84 { |
| 85 ASSERT(element.parentNode()); |
| 86 return ensureNthIndexDataFor(*element.parentNode()).nthLastIndex(element); |
| 87 } |
| 88 |
| 89 } // namespace blink |
| 90 |
| 91 #endif // NthIndexCache_h |
OLD | NEW |