forked from zeromq/goczmq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
poller.go
103 lines (92 loc) · 2.27 KB
/
poller.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
package goczmq
/*
#include "czmq.h"
zpoller_t *Poller_new(void *reader) {
zpoller_t *poller = zpoller_new(reader, NULL);
return poller;
}
*/
import "C"
import (
"fmt"
"unsafe"
)
// Poller provides a simple wrapper to ZeroMQ's zmq_poll API,
// for the common case of reading from a number of sockets.
// Sockets can be added and removed from the running poller.
type Poller struct {
zpollerT *C.struct__zpoller_t
socks []*Sock
}
// NewPoller creates a new Poller instance.
// It accepts one or more readers to poll.
func NewPoller(readers ...*Sock) (*Poller, error) {
var p *Poller
if len(readers) == 0 {
p = &Poller{
zpollerT: C.Poller_new(nil),
socks: make([]*Sock, 0),
}
} else {
p = &Poller{
zpollerT: C.Poller_new(unsafe.Pointer(readers[0].zsockT)),
socks: make([]*Sock, 0),
}
p.socks = append(p.socks, readers[0])
if len(readers) == 1 {
return p, nil
}
for _, reader := range readers[1:] {
err := p.Add(reader)
if err != nil {
return nil, err
}
}
}
return p, nil
}
// Add adds a reader to be polled.
func (p *Poller) Add(reader *Sock) error {
rc := C.zpoller_add(p.zpollerT, unsafe.Pointer(reader.zsockT))
if int(rc) == -1 {
return fmt.Errorf("error adding reader")
}
p.socks = append(p.socks, reader)
return nil
}
// Remove removes a Sock from the poller
func (p *Poller) Remove(reader *Sock) {
numItems := len(p.socks)
for i := 0; i < numItems; i++ {
if p.socks[i] == reader {
if i == numItems-1 {
p.socks = p.socks[:i]
} else {
p.socks = append(p.socks[:i], p.socks[i+1:]...)
}
}
}
}
// Wait waits for the timeout period in milliseconds for a Pollin
// event, and returns the first socket that returns one
func (p *Poller) Wait(millis int) (*Sock, error) {
if p.zpollerT == nil {
// Null pointer. Something is wrong or we've already had `Destroy` invoked on us.
return nil, ErrWaitAfterDestroy
}
s := C.zpoller_wait(p.zpollerT, C.int(millis))
s = unsafe.Pointer(s)
if s == nil {
return nil, nil
}
for _, sock := range p.socks {
if unsafe.Pointer(sock.zsockT) == s {
return sock, nil
}
}
return nil, fmt.Errorf("Could not match received pointer with %v with any socket (%v)", s, p.socks)
}
// Destroy destroys the Poller
func (p *Poller) Destroy() {
C.zpoller_destroy(&p.zpollerT)
}