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