File: filter.go

package info (click to toggle)
golang-github-docker-go-events 0.0~git20190806.e31b211-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-proposed-updates, sid, trixie
  • size: 148 kB
  • sloc: makefile: 2
file content (52 lines) | stat: -rw-r--r-- 1,111 bytes parent folder | download | duplicates (4)
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
package events

// Matcher matches events.
type Matcher interface {
	Match(event Event) bool
}

// MatcherFunc implements matcher with just a function.
type MatcherFunc func(event Event) bool

// Match calls the wrapped function.
func (fn MatcherFunc) Match(event Event) bool {
	return fn(event)
}

// Filter provides an event sink that sends only events that are accepted by a
// Matcher. No methods on filter are goroutine safe.
type Filter struct {
	dst     Sink
	matcher Matcher
	closed  bool
}

// NewFilter returns a new filter that will send to events to dst that return
// true for Matcher.
func NewFilter(dst Sink, matcher Matcher) Sink {
	return &Filter{dst: dst, matcher: matcher}
}

// Write an event to the filter.
func (f *Filter) Write(event Event) error {
	if f.closed {
		return ErrSinkClosed
	}

	if f.matcher.Match(event) {
		return f.dst.Write(event)
	}

	return nil
}

// Close the filter and allow no more events to pass through.
func (f *Filter) Close() error {
	// TODO(stevvooe): Not all sinks should have Close.
	if f.closed {
		return nil
	}

	f.closed = true
	return f.dst.Close()
}