Debian Codegraph @

match.go

raw
1 package enmime
2
3 import (
4 "container/list"
5 )
6
7 // PartMatcher is a function type that you must implement to search for Parts using the
8 // BreadthMatch* functions. Implementators should inspect the provided Part and return true if it
9 // matches your criteria.
10 type PartMatcher func(part *Part) bool
11
12 // BreadthMatchFirst performs a breadth first search of the Part tree and returns the first part
13 // that causes the given matcher to return true
14 func (p *Part) BreadthMatchFirst(matcher PartMatcher) *Part {
15 q := list.New()
16 q.PushBack(p)
17
18 // Push children onto queue and attempt to match in that order
19 for q.Len() > 0 {
20 e := q.Front()
21 p := e.Value.(*Part)
22 if matcher(p) {
23 return p
24 }
25 q.Remove(e)
26 c := p.FirstChild
27 for c != nil {
28 q.PushBack(c)
29 c = c.NextSibling
30 }
31 }
32
33 return nil
34 }
35
36 // BreadthMatchAll performs a breadth first search of the Part tree and returns all parts that cause
37 // the given matcher to return true
38 func (p *Part) BreadthMatchAll(matcher PartMatcher) []*Part {
39 q := list.New()
40 q.PushBack(p)
41
42 matches := make([]*Part, 0, 10)
43
44 // Push children onto queue and attempt to match in that order
45 for q.Len() > 0 {
46 e := q.Front()
47 p := e.Value.(*Part)
48 if matcher(p) {
49 matches = append(matches, p)
50 }
51 q.Remove(e)
52 c := p.FirstChild
53 for c != nil {
54 q.PushBack(c)
55 c = c.NextSibling
56 }
57 }
58
59 return matches
60 }
61
62 // DepthMatchFirst performs a depth first search of the Part tree and returns the first part that
63 // causes the given matcher to return true
64 func (p *Part) DepthMatchFirst(matcher PartMatcher) *Part {
65 root := p
66 for {
67 if matcher(p) {
68 return p
69 }
70 c := p.FirstChild
71 if c != nil {
72 p = c
73 } else {
74 for p.NextSibling == nil {
75 if p == root {
76 return nil
77 }
78 p = p.Parent
79 }
80 p = p.NextSibling
81 }
82 }
83 }
84
85 // DepthMatchAll performs a depth first search of the Part tree and returns all parts that causes
86 // the given matcher to return true
87 func (p *Part) DepthMatchAll(matcher PartMatcher) []*Part {
88 root := p
89 matches := make([]*Part, 0, 10)
90 for {
91 if matcher(p) {
92 matches = append(matches, p)
93 }
94 c := p.FirstChild
95 if c != nil {
96 p = c
97 } else {
98 for p.NextSibling == nil {
99 if p == root {
100 return matches
101 }
102 p = p.Parent
103 }
104 p = p.NextSibling
105 }
106 }
107 }