Skip to content

Commit

Permalink
use closeOnError pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
brycekahle committed Jun 21, 2024
1 parent 9782078 commit 1d16d24
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions internal/epoll/poller.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,37 +27,42 @@ type Poller struct {
flushEvent *eventFd
}

func New() (*Poller, error) {
func New() (_ *Poller, err error) {
closeFDOnError := func(fd int) {
if err != nil {
unix.Close(fd)
}
}
closeEventFDOnError := func(e *eventFd) {
if err != nil {
e.close()
}
}

epollFd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC)
if err != nil {
return nil, fmt.Errorf("create epoll fd: %v", err)
}
defer closeFDOnError(epollFd)

p := &Poller{epollFd: epollFd}
p.closeEvent, err = newEventFd()
if err != nil {
unix.Close(epollFd)
return nil, err
}
defer closeEventFDOnError(p.closeEvent)

p.flushEvent, err = newEventFd()
if err != nil {
p.closeEvent.close()
unix.Close(epollFd)
return nil, err
}
defer closeEventFDOnError(p.flushEvent)

if err := p.Add(p.closeEvent.raw, 0); err != nil {
unix.Close(epollFd)
p.closeEvent.close()
p.flushEvent.close()
return nil, fmt.Errorf("add close eventfd: %w", err)
}

if err := p.Add(p.flushEvent.raw, 0); err != nil {
unix.Close(epollFd)
p.closeEvent.close()
p.flushEvent.close()
return nil, fmt.Errorf("add flush eventfd: %w", err)
}

Expand Down

0 comments on commit 1d16d24

Please sign in to comment.