diff options
| author | Stefan Behnel <stefan_ml@behnel.de> | 2014-08-28 15:52:08 +0200 |
|---|---|---|
| committer | Stefan Behnel <stefan_ml@behnel.de> | 2014-08-28 15:52:08 +0200 |
| commit | 70829fa58a8deca8d82f855756c554bcaa4e108a (patch) | |
| tree | 620376ce0271f75d9cb41afabead416c8ac4d1aa /src/lxml/apihelpers.pxi | |
| parent | beab69f059d24b7cdc03d7df4a70c551f6835192 (diff) | |
| download | python-lxml-70829fa58a8deca8d82f855756c554bcaa4e108a.tar.gz | |
refactor some duplicated code
Diffstat (limited to 'src/lxml/apihelpers.pxi')
| -rw-r--r-- | src/lxml/apihelpers.pxi | 34 |
1 files changed, 16 insertions, 18 deletions
diff --git a/src/lxml/apihelpers.pxi b/src/lxml/apihelpers.pxi index 8e160015..66b4f25b 100644 --- a/src/lxml/apihelpers.pxi +++ b/src/lxml/apihelpers.pxi @@ -74,6 +74,13 @@ cdef _Element _rootNodeOrRaise(object input): _assertValidNode(node) return node +cdef bint _isAncestorOrSame(xmlNode* c_ancestor, xmlNode* c_node): + while c_node: + if c_node is c_ancestor: + return True + c_node = c_node.parent + return False + cdef _Element _makeElement(tag, xmlDoc* c_doc, _Document doc, _BaseParser parser, text, tail, attrib, nsmap, dict extra_attrs): @@ -1243,11 +1250,8 @@ cdef int _appendChild(_Element parent, _Element child) except -1: c_node = child._c_node c_source_doc = c_node.doc # prevent cycles - c_parent = parent._c_node - while c_parent: - if c_parent is c_node: - raise ValueError("cannot append parent to itself") - c_parent = c_parent.parent + if _isAncestorOrSame(c_node, parent._c_node): + raise ValueError("cannot append parent to itself") # store possible text node c_next = c_node.next # move node itself @@ -1265,11 +1269,8 @@ cdef int _prependChild(_Element parent, _Element child) except -1: c_node = child._c_node c_source_doc = c_node.doc # prevent cycles - c_parent = parent._c_node - while c_parent: - if c_parent is c_node: - raise ValueError("cannot append parent to itself") - c_parent = c_parent.parent + if _isAncestorOrSame(c_node, parent._c_node): + raise ValueError("cannot append parent to itself") # store possible text node c_next = c_node.next # move node itself @@ -1297,15 +1298,12 @@ cdef int _prependSibling(_Element element, _Element sibling) except -1: cdef int _addSibling(_Element element, _Element sibling, bint as_next) except -1: c_node = sibling._c_node - if element._c_node is c_node: - return 0 # nothing to do c_source_doc = c_node.doc - # detect cycles - c_parent = element._c_node.parent - while c_parent: - if c_parent is c_node: - raise ValueError("cannot add ancestor as sibling, please break cycle first") - c_parent = c_parent.parent + # prevent cycles + if _isAncestorOrSame(c_node, element._c_node): + if element._c_node is c_node: + return 0 # nothing to do + raise ValueError("cannot add ancestor as sibling, please break cycle first") # store possible text node c_next = c_node.next # move node itself |
