Issue #2401 - Part 1: Templatize GetCommonAncestor.

This commit is contained in:
Moonchild 2024-01-09 11:30:23 +01:00 • committed by roytam1
commit a73c8e93d6
2 changed files with 23 additions and 14 deletions

View file

@ -2395,34 +2395,35 @@ nsContentUtils::GetCommonAncestor(nsIDOMNode *aNode,
return CallQueryInterface(common, aCommonAncestor); return CallQueryInterface(common, aCommonAncestor);
} }
// static template <typename Node, typename GetParentFunc>
nsINode* static Node*
nsContentUtils::GetCommonAncestor(nsINode* aNode1, GetCommonAncestorInternal(Node* aNode1,
nsINode* aNode2) Node* aNode2,
GetParentFunc aGetParentFunc)
{ {
if (aNode1 == aNode2) { if (aNode1 == aNode2) {
return aNode1; return aNode1;
} }
// Build the chain of parents // Build the chain of parents
AutoTArray<nsINode*, 30> parents1, parents2; AutoTArray<Node*, 30> parents1, parents2;
do { do {
parents1.AppendElement(aNode1); parents1.AppendElement(aNode1);
aNode1 = aNode1->GetParentNode(); aNode1 = aGetParentFunc(aNode1);
} while (aNode1); } while (aNode1);
do { do {
parents2.AppendElement(aNode2); parents2.AppendElement(aNode2);
aNode2 = aNode2->GetParentNode(); aNode2 = aGetParentFunc(aNode2);
} while (aNode2); } while (aNode2);
// Find where the parent chain differs // Find where the parent chain differs
uint32_t pos1 = parents1.Length(); uint32_t pos1 = parents1.Length();
uint32_t pos2 = parents2.Length(); uint32_t pos2 = parents2.Length();
nsINode* parent = nullptr; Node* parent = nullptr;
uint32_t len; uint32_t len;
for (len = std::min(pos1, pos2); len > 0; --len) { for (len = std::min(pos1, pos2); len > 0; --len) {
nsINode* child1 = parents1.ElementAt(--pos1); Node* child1 = parents1.ElementAt(--pos1);
nsINode* child2 = parents2.ElementAt(--pos2); Node* child2 = parents2.ElementAt(--pos2);
if (child1 != child2) { if (child1 != child2) {
break; break;
} }
@ -2432,6 +2433,15 @@ nsContentUtils::GetCommonAncestor(nsINode* aNode1,
return parent; return parent;
} }
/* static */
nsINode*
nsContentUtils::GetCommonAncestor(nsINode* aNode1, nsINode* aNode2)
{
return GetCommonAncestorInternal(aNode1, aNode2, [](nsINode* aNode) {
return aNode->GetParentNode();
});
}
// static // static
nsINode* nsINode*
nsContentUtils::GetCommonAncestorUnderInteractiveContent(nsINode* aNode1, nsContentUtils::GetCommonAncestorUnderInteractiveContent(nsINode* aNode1,

View file

@ -333,11 +333,10 @@ public:
nsIDOMNode** aCommonAncestor); nsIDOMNode** aCommonAncestor);
/** /**
* Returns the common ancestor, if any, for two nodes. Returns null if the * Returns the common ancestor, if any, for two nodes.
* nodes are disconnected. * Returns null if the nodes are disconnected.
*/ */
static nsINode* GetCommonAncestor(nsINode* aNode1, static nsINode* GetCommonAncestor(nsINode* aNode1, nsINode* aNode2);
nsINode* aNode2);
/** /**
* Returns the common ancestor under interactive content, if any. * Returns the common ancestor under interactive content, if any.