home *** CD-ROM | disk | FTP | other *** search
/ Chip 2006 June / CHIP 2006-06.2.iso / program / freeware / Democracy-0.8.2.exe / xulrunner / python / BitTorrent / selectpoll.py < prev    next >
Encoding:
Python Source  |  2006-04-10  |  1.9 KB  |  69 lines

  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.0 (the License).  You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License.  You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10.  
  11. # Written by Bram Cohen
  12.  
  13. from select import select, error
  14. from time import sleep
  15. from types import IntType
  16. from bisect import bisect
  17. POLLIN = 1
  18. POLLOUT = 2
  19. POLLERR = 8
  20. POLLHUP = 16
  21.  
  22.  
  23. class poll(object):
  24.  
  25.     def __init__(self):
  26.         self.rlist = []
  27.         self.wlist = []
  28.         
  29.     def register(self, f, t):
  30.         if type(f) != IntType:
  31.             f = f.fileno()
  32.         if (t & POLLIN) != 0:
  33.             insert(self.rlist, f)
  34.         else:
  35.             remove(self.rlist, f)
  36.         if (t & POLLOUT) != 0:
  37.             insert(self.wlist, f)
  38.         else:
  39.             remove(self.wlist, f)
  40.         
  41.     def unregister(self, f):
  42.         if type(f) != IntType:
  43.             f = f.fileno()
  44.         remove(self.rlist, f)
  45.         remove(self.wlist, f)
  46.  
  47.     def poll(self, timeout = None):
  48.         if self.rlist != [] or self.wlist != []:
  49.             r, w, e = select(self.rlist, self.wlist, [], timeout)
  50.         else:
  51.             sleep(timeout)
  52.             return []
  53.         result = []
  54.         for s in r:
  55.             result.append((s, POLLIN))
  56.         for s in w:
  57.             result.append((s, POLLOUT))
  58.         return result
  59.  
  60. def remove(list, item):
  61.     i = bisect(list, item)
  62.     if i > 0 and list[i-1] == item:
  63.         del list[i-1]
  64.  
  65. def insert(list, item):
  66.     i = bisect(list, item)
  67.     if i == 0 or list[i-1] != item:
  68.         list.insert(i, item)
  69.