-
Notifications
You must be signed in to change notification settings - Fork 0
/
kqueue_darwin.go
66 lines (59 loc) · 1.65 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
66
package event_loop
import (
"fmt"
"syscall"
"time"
)
// KQueue represents KQueue for BSD systems.
// fd represents the file descriptor for the kernel KQueue.
type KQueue struct {
fd int
kQEvents []syscall.Kevent_t
}
// NewKQueue creates a new instance of KQueue.
// syscall.Kqueue() creates the Kernel KQueue which can be polled using syscall.Kevent().
func NewKQueue(maxClients int) (*KQueue, error) {
fd, err := syscall.Kqueue()
if err != nil {
return nil, err
}
return &KQueue{
fd: fd,
kQEvents: make([]syscall.Kevent_t, maxClients),
}, nil
}
// Subscribe subscribes to an event of type syscall.Kevent_t.
func (kq *KQueue) Subscribe(event syscall.Kevent_t) error {
if subscribed, err := syscall.Kevent(
kq.fd,
[]syscall.Kevent_t{event},
nil,
nil,
); err != nil || subscribed == -1 {
return fmt.Errorf("error in subscribing to KQueue: %w", err)
}
return nil
}
// Poll polls the Kernel KQueue for the specified duration using Kevent syscall.
// The method "blocks" until at least one event is triggered or the timeout is reached.
// This is the only blocking call in this module.
func (kq *KQueue) Poll(timeout time.Duration) ([]syscall.Kevent_t, error) {
n, err := syscall.Kevent(kq.fd, nil, kq.kQEvents, toTimeSpec(timeout))
if err != nil {
return nil, fmt.Errorf("error in KQueue poll: %w", err)
}
return kq.kQEvents[:n], nil
}
// Close closes the KQueue.
func (kq *KQueue) Close() error {
return syscall.Close(kq.fd)
}
// toTimeSpec converts the duration to syscall.Timespec.
func toTimeSpec(duration time.Duration) *syscall.Timespec {
if duration < 0 {
return nil
}
return &syscall.Timespec{
Nsec: int64(duration),
}
}