select.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "time"
  5. "golang.org/x/sys/unix"
  6. )
  7. type Selector struct {
  8. read_set, write_set, err_set unix.FdSet
  9. read_fds, write_fds, err_fds map[int]bool
  10. }
  11. func CreateSelect(expected_number_of_fds int) *Selector {
  12. var ans Selector
  13. ans.read_fds = make(map[int]bool, expected_number_of_fds)
  14. ans.write_fds = make(map[int]bool, expected_number_of_fds)
  15. ans.err_fds = make(map[int]bool, expected_number_of_fds)
  16. return &ans
  17. }
  18. func (self *Selector) register(fd int, fdset *map[int]bool) {
  19. (*fdset)[fd] = true
  20. }
  21. func (self *Selector) RegisterRead(fd int) {
  22. self.register(fd, &self.read_fds)
  23. }
  24. func (self *Selector) RegisterWrite(fd int) {
  25. self.register(fd, &self.write_fds)
  26. }
  27. func (self *Selector) RegisterError(fd int) {
  28. self.register(fd, &self.err_fds)
  29. }
  30. func (self *Selector) unregister(fd int, fdset *map[int]bool) {
  31. (*fdset)[fd] = false
  32. }
  33. func (self *Selector) UnRegisterRead(fd int) {
  34. self.unregister(fd, &self.read_fds)
  35. }
  36. func (self *Selector) UnRegisterWrite(fd int) {
  37. self.unregister(fd, &self.write_fds)
  38. }
  39. func (self *Selector) UnRegisterError(fd int) {
  40. self.unregister(fd, &self.err_fds)
  41. }
  42. func (self *Selector) Wait(timeout time.Duration) (num_ready int, err error) {
  43. max_fd_num := 0
  44. init_set := func(s *unix.FdSet, m map[int]bool) {
  45. s.Zero()
  46. for fd, enabled := range m {
  47. if fd > -1 && enabled {
  48. if max_fd_num < fd {
  49. max_fd_num = fd
  50. }
  51. s.Set(fd)
  52. }
  53. }
  54. }
  55. init_set(&self.read_set, self.read_fds)
  56. init_set(&self.write_set, self.write_fds)
  57. init_set(&self.err_set, self.err_fds)
  58. num_ready, err = Select(max_fd_num+1, &self.read_set, &self.write_set, &self.err_set, timeout)
  59. if err == unix.EINTR {
  60. self.read_set.Zero()
  61. self.write_set.Zero()
  62. self.err_set.Zero()
  63. return 0, err
  64. }
  65. return
  66. }
  67. func (self *Selector) WaitForever() (num_ready int, err error) {
  68. return self.Wait(-1)
  69. }
  70. func (self *Selector) IsReadyToRead(fd int) bool {
  71. return fd > -1 && self.read_set.IsSet(fd)
  72. }
  73. func (self *Selector) IsReadyToWrite(fd int) bool {
  74. return fd > -1 && self.write_set.IsSet(fd)
  75. }
  76. func (self *Selector) IsErrored(fd int) bool {
  77. return fd > -1 && self.err_set.IsSet(fd)
  78. }
  79. func (self *Selector) UnregisterAll() {
  80. self.read_fds = make(map[int]bool)
  81. self.write_fds = make(map[int]bool)
  82. self.err_fds = make(map[int]bool)
  83. }