File: match.go

package info (click to toggle)
golang-github-jhillyerd-enmime 0.9.3-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,156 kB
  • sloc: makefile: 25; sh: 16
file content (107 lines) | stat: -rw-r--r-- 2,282 bytes parent folder | download | duplicates (2)
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"
)

// PartMatcher is a function type that you must implement to search for Parts using the
// BreadthMatch* functions.  Implementators should inspect the provided Part and return true if it
// matches your criteria.
type PartMatcher func(part *Part) bool

// BreadthMatchFirst performs a breadth first search of the Part tree and returns the first part
// that causes the given matcher to return true
func (p *Part) BreadthMatchFirst(matcher PartMatcher) *Part {
	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.(*Part)
		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 Part tree and returns all parts that cause
// the given matcher to return true
func (p *Part) BreadthMatchAll(matcher PartMatcher) []*Part {
	q := list.New()
	q.PushBack(p)

	matches := make([]*Part, 0, 10)

	// Push children onto queue and attempt to match in that order
	for q.Len() > 0 {
		e := q.Front()
		p := e.Value.(*Part)
		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 Part tree and returns the first part that
// causes the given matcher to return true
func (p *Part) DepthMatchFirst(matcher PartMatcher) *Part {
	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 Part tree and returns all parts that causes
// the given matcher to return true
func (p *Part) DepthMatchAll(matcher PartMatcher) []*Part {
	root := p
	matches := make([]*Part, 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
		}
	}
}