High level interface for low level file descriptor polling
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

descriptor.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package poll
  2. import (
  3. "net"
  4. "os"
  5. "syscall"
  6. )
  7. type Descriptor struct {
  8. *os.File
  9. Event
  10. }
  11. func NewDescriptor(fd uintptr, ev Event) *Descriptor {
  12. return &Descriptor{
  13. File: os.NewFile(fd, ""),
  14. Event: ev,
  15. }
  16. }
  17. func (d Descriptor) fd() int {
  18. return int(d.Fd())
  19. }
  20. func Handle(c net.Conn, events Event) (*Descriptor, error) {
  21. d, err := handle(c, events)
  22. if err != nil {
  23. return nil, err
  24. }
  25. if err = syscall.SetNonblock(d.fd(), true); err != nil {
  26. return nil, os.NewSyscallError("setnonblock", err)
  27. }
  28. return d, nil
  29. }
  30. func HandleRead(c net.Conn) (*Descriptor, error) {
  31. return Handle(c, EventRead|EventEdgeTriggered)
  32. }
  33. func HandleReadOnce(c net.Conn) (*Descriptor, error) {
  34. return Handle(c, EventRead|EventOneShot)
  35. }
  36. func HandleWrite(c net.Conn) (*Descriptor, error) {
  37. return Handle(c, EventWrite|EventEdgeTriggered)
  38. }
  39. func HandleWriteOnce(c net.Conn) (*Descriptor, error) {
  40. return Handle(c, EventWrite|EventOneShot)
  41. }
  42. func HandleReadWrite(c net.Conn) (*Descriptor, error) {
  43. return Handle(c, EventRead|EventWrite|EventEdgeTriggered)
  44. }
  45. func handle(x interface{}, events Event) (*Descriptor, error) {
  46. i, ok := x.(filer)
  47. if !ok {
  48. return nil, ErrNotFiler
  49. }
  50. f, err := i.File()
  51. if err != nil {
  52. return nil, err
  53. }
  54. return &Descriptor{
  55. File: f,
  56. Event: events,
  57. }, nil
  58. }