forked from DiceDB/dice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkqueue_darwin.go
65 lines (55 loc) · 1.69 KB
/
kqueue_darwin.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
package iomultiplexer
import (
"fmt"
"syscall"
"time"
)
// KQueue implements the IOMultiplexer interface for Darwin-based systems
type KQueue struct {
// fd stores the file descriptor of the kqueue instance
fd int
// kQEvents acts as a buffer for the events returned by the Kevent syscall
kQEvents []syscall.Kevent_t
// diceEvents stores the events after they are converted to the generic Event type
// and is returned to the caller
diceEvents []Event
}
// New creates a new KQueue instance
func New(maxClients int) (*KQueue, error) {
if maxClients < 0 {
return nil, ErrInvalidMaxClients
}
fd, err := syscall.Kqueue()
if err != nil {
return nil, err
}
return &KQueue{
fd: fd,
kQEvents: make([]syscall.Kevent_t, maxClients),
diceEvents: make([]Event, maxClients),
}, nil
}
// Subscribe subscribes to the given event
func (kq *KQueue) Subscribe(event Event) error {
if subscribed, err := syscall.Kevent(kq.fd, []syscall.Kevent_t{event.toNative(syscall.EV_ADD)}, nil, nil); err != nil || subscribed == -1 {
return fmt.Errorf("kqueue subscribe: %w", err)
}
return nil
}
// Poll polls for all the subscribed events simultaneously
// and returns all the events that were triggered
// It blocks until at least one event is triggered or the timeout is reached
func (kq *KQueue) Poll(timeout time.Duration) ([]Event, error) {
nEvents, err := syscall.Kevent(kq.fd, nil, kq.kQEvents, newTime(timeout))
if err != nil {
return nil, fmt.Errorf("kqueue poll: %w", err)
}
for i := 0; i < nEvents; i++ {
kq.diceEvents[i] = newEvent(kq.kQEvents[i])
}
return kq.diceEvents[:nEvents], nil
}
// Close closes the KQueue instance
func (kq *KQueue) Close() error {
return syscall.Close(kq.fd)
}