github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/poller/netpoll/netpoll_epoll.go (about)

     1  // +build linux
     2  
     3  package netpoll
     4  
     5  import (
     6  	"os"
     7  )
     8  
     9  // New creates new epoll-based Poller instance with given config.
    10  func New(c *Config) (Poller, error) {
    11  	cfg := c.withDefaults()
    12  
    13  	epoll, err := EpollCreate(&EpollConfig{
    14  		OnWaitError: cfg.OnWaitError,
    15  	})
    16  	if err != nil {
    17  		return nil, err
    18  	}
    19  
    20  	return poller{epoll}, nil
    21  }
    22  
    23  // poller implements Poller interface.
    24  type poller struct {
    25  	*Epoll
    26  }
    27  
    28  // Start implements Poller.Start() method.
    29  func (ep poller) Start(desc *Desc, cb CallbackFn) error {
    30  	err := ep.Add(desc.fd(), toEpollEvent(desc.event),
    31  		func(ep EpollEvent) {
    32  			var event Event
    33  
    34  			if ep&EPOLLHUP != 0 {
    35  				event |= EventHup
    36  			}
    37  			if ep&EPOLLRDHUP != 0 {
    38  				event |= EventReadHup
    39  			}
    40  			if ep&EPOLLIN != 0 {
    41  				event |= EventRead
    42  			}
    43  			if ep&EPOLLOUT != 0 {
    44  				event |= EventWrite
    45  			}
    46  			if ep&EPOLLERR != 0 {
    47  				event |= EventErr
    48  			}
    49  			if ep&_EPOLLCLOSED != 0 {
    50  				event |= EventPollerClosed
    51  			}
    52  
    53  			cb(event)
    54  		},
    55  	)
    56  	if err == nil {
    57  		if err = setNonblock(desc.fd(), true); err != nil {
    58  			return os.NewSyscallError("setnonblock", err)
    59  		}
    60  	}
    61  	return err
    62  }
    63  
    64  // Stop implements Poller.Stop() method.
    65  func (ep poller) Stop(desc *Desc) error {
    66  	return ep.Del(desc.fd())
    67  }
    68  
    69  // Resume implements Poller.Resume() method.
    70  func (ep poller) Resume(desc *Desc) error {
    71  	return ep.Mod(desc.fd(), toEpollEvent(desc.event))
    72  }
    73  
    74  func toEpollEvent(event Event) (ep EpollEvent) {
    75  	if event&EventRead != 0 {
    76  		ep |= EPOLLIN | EPOLLRDHUP
    77  	}
    78  	if event&EventWrite != 0 {
    79  		ep |= EPOLLOUT
    80  	}
    81  	if event&EventOneShot != 0 {
    82  		ep |= EPOLLONESHOT
    83  	}
    84  	if event&EventEdgeTriggered != 0 {
    85  		ep |= EPOLLET
    86  	}
    87  	return ep
    88  }