File: channel.go

package info (click to toggle)
golang-github-docker-go-events 0.0~git20160331.0.882f161-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 120 kB
  • ctags: 86
  • sloc: makefile: 2
file content (47 lines) | stat: -rw-r--r-- 1,019 bytes parent folder | download
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
package events

// Channel provides a sink that can be listened on. The writer and channel
// listener must operate in separate goroutines.
//
// Consumers should listen on Channel.C until Closed is closed.
type Channel struct {
	C chan Event

	closed chan struct{}
}

// NewChannel returns a channel. If buffer is non-zero, the channel is
// unbuffered.
func NewChannel(buffer int) *Channel {
	return &Channel{
		C:      make(chan Event, buffer),
		closed: make(chan struct{}),
	}
}

// Done returns a channel that will always proceed once the sink is closed.
func (ch *Channel) Done() chan struct{} {
	return ch.closed
}

// Write the event to the channel. Must be called in a separate goroutine from
// the listener.
func (ch *Channel) Write(event Event) error {
	select {
	case ch.C <- event:
		return nil
	case <-ch.closed:
		return ErrSinkClosed
	}
}

// Close the channel sink.
func (ch *Channel) Close() error {
	select {
	case <-ch.closed:
		return ErrSinkClosed
	default:
		close(ch.closed)
		return nil
	}
}