rss-tools/vendor/golang.org/x/net/html/iter.go (view raw)
| 1 | // Copyright 2024 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package html |
| 6 | |
| 7 | import "iter" |
| 8 | |
| 9 | // Ancestors returns an iterator over the ancestors of n, starting with n.Parent. |
| 10 | // |
| 11 | // Mutating a Node or its parents while iterating may have unexpected results. |
| 12 | func (n *Node) Ancestors() iter.Seq[*Node] { |
| 13 | _ = n.Parent // eager nil check |
| 14 | |
| 15 | return func(yield func(*Node) bool) { |
| 16 | for p := n.Parent; p != nil && yield(p); p = p.Parent { |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | // ChildNodes returns an iterator over the immediate children of n, |
| 22 | // starting with n.FirstChild. |
| 23 | // |
| 24 | // Mutating a Node or its children while iterating may have unexpected results. |
| 25 | func (n *Node) ChildNodes() iter.Seq[*Node] { |
| 26 | _ = n.FirstChild // eager nil check |
| 27 | |
| 28 | return func(yield func(*Node) bool) { |
| 29 | for c := n.FirstChild; c != nil && yield(c); c = c.NextSibling { |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | } |
| 34 | |
| 35 | // Descendants returns an iterator over all nodes recursively beneath |
| 36 | // n, excluding n itself. Nodes are visited in depth-first preorder. |
| 37 | // |
| 38 | // Mutating a Node or its descendants while iterating may have unexpected results. |
| 39 | func (n *Node) Descendants() iter.Seq[*Node] { |
| 40 | _ = n.FirstChild // eager nil check |
| 41 | |
| 42 | return func(yield func(*Node) bool) { |
| 43 | n.descendants(yield) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func (n *Node) descendants(yield func(*Node) bool) bool { |
| 48 | for c := range n.ChildNodes() { |
| 49 | if !yield(c) || !c.descendants(yield) { |
| 50 | return false |
| 51 | } |
| 52 | } |
| 53 | return true |
| 54 | } |