Subversion Repositories svnkaklik

Rev

Details | Last modification | View Log

Rev Author Line No. Line
36 kaklik 1
# Written by Bram Cohen
2
# see LICENSE.txt for license information
3
 
4
from select import select, error
5
from time import sleep
6
from types import IntType
7
from bisect import bisect
8
POLLIN = 1
9
POLLOUT = 2
10
POLLERR = 8
11
POLLHUP = 16
12
 
13
class poll:
14
    def __init__(self):
15
        self.rlist = []
16
        self.wlist = []
17
 
18
    def register(self, f, t):
19
        if type(f) != IntType:
20
            f = f.fileno()
21
        if (t & POLLIN):
22
            insert(self.rlist, f)
23
        else:
24
            remove(self.rlist, f)
25
        if (t & POLLOUT):
26
            insert(self.wlist, f)
27
        else:
28
            remove(self.wlist, f)
29
 
30
    def unregister(self, f):
31
        if type(f) != IntType:
32
            f = f.fileno()
33
        remove(self.rlist, f)
34
        remove(self.wlist, f)
35
 
36
    def poll(self, timeout = None):
37
        if self.rlist or self.wlist:
38
            try:
39
                r, w, e = select(self.rlist, self.wlist, [], timeout)
40
            except ValueError:
41
                return None
42
        else:
43
            sleep(timeout)
44
            return []
45
        result = []
46
        for s in r:
47
            result.append((s, POLLIN))
48
        for s in w:
49
            result.append((s, POLLOUT))
50
        return result
51
 
52
def remove(list, item):
53
    i = bisect(list, item)
54
    if i > 0 and list[i-1] == item:
55
        del list[i-1]
56
 
57
def insert(list, item):
58
    i = bisect(list, item)
59
    if i == 0 or list[i-1] != item:
60
        list.insert(i, item)
61
 
62
def test_remove():
63
    x = [2, 4, 6]
64
    remove(x, 2)
65
    assert x == [4, 6]
66
    x = [2, 4, 6]
67
    remove(x, 4)
68
    assert x == [2, 6]
69
    x = [2, 4, 6]
70
    remove(x, 6)
71
    assert x == [2, 4]
72
    x = [2, 4, 6]
73
    remove(x, 5)
74
    assert x == [2, 4, 6]
75
    x = [2, 4, 6]
76
    remove(x, 1)
77
    assert x == [2, 4, 6]
78
    x = [2, 4, 6]
79
    remove(x, 7)
80
    assert x == [2, 4, 6]
81
    x = [2, 4, 6]
82
    remove(x, 5)
83
    assert x == [2, 4, 6]
84
    x = []
85
    remove(x, 3)
86
    assert x == []
87
 
88
def test_insert():
89
    x = [2, 4]
90
    insert(x, 1)
91
    assert x == [1, 2, 4]
92
    x = [2, 4]
93
    insert(x, 3)
94
    assert x == [2, 3, 4]
95
    x = [2, 4]
96
    insert(x, 5)
97
    assert x == [2, 4, 5]
98
    x = [2, 4]
99
    insert(x, 2)
100
    assert x == [2, 4]
101
    x = [2, 4]
102
    insert(x, 4)
103
    assert x == [2, 4]
104
    x = [2, 3, 4]
105
    insert(x, 3)
106
    assert x == [2, 3, 4]
107
    x = []
108
    insert(x, 3)
109
    assert x == [3]