Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/dobject_helpers.py
blob: f87c7ed0a2b6a63ad8172fa0cf1dd8f2b5101ce8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""
Copyright 2008 Benjamin M. Schwartz

This file is LGPLv2+.  This file, dobject_helpers.py, is part of DObject.

DObject is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

DObject is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with DObject.  If not, see <http://www.gnu.org/licenses/>.
"""

import bisect

"""
dobject_helpers is a collection of functions and data structures that are useful
to DObject, but are not specific to DBus or networked applications.
"""

def merge(a, b, l=True, g=True, e=True):
    """Internal helper function for combining sets represented as sorted lists"""
    x = 0
    X = len(a)
    if X == 0:
        if g:
            return list(b)
        else:
            return []
    y = 0
    Y = len(b)
    if Y == 0:
        if l:
            return list(a)
        else:
            return []
    out = []
    p = a[x]
    q = b[y]
    while x < X and y < Y:
        if p < q:
            if l: out.append(p)
            x += 1
            if x < X: p = a[x]
        elif p > q:
            if g: out.append(q)
            y += 1
            if y < Y: q = b[y]
        else:
            if e: out.append(p)
            x += 1
            if x < X: p = a[x]
            y += 1
            if y < Y: q = b[y]       
    if x < X:
        if l: out.extend(a[x:])
    else:
        if g: out.extend(b[y:])
    return out

def merge_or(a,b):
    return merge(a,b, True, True, True)

def merge_xor(a,b):
    return merge(a, b, True, True, False)

def merge_and(a,b):
    return merge(a, b, False, False, True)

def merge_sub(a,b):
    return merge(a, b, True, False, False)

def kill_dupes(a): #assumes a is sorted
    """Internal helper function for removing duplicates in a sorted list"""
    prev = a[0]
    out = [prev]
    for i in xrange(1, len(a)):
        item = a[i]
        if item != prev:
            out.append(item)
            prev = item
    return out

class Comparable:
    """Currently, ListSet does not provide a mechanism for specifying a
    comparator.  Users who would like to specify a comparator other than the one
    native to the item may do so by wrapping the item in a Comparable.
    """
    def __init__(self, item, comparator):
        self.item = item
        self._cmp = comparator
    
    def __cmp__(self, other):
        return self._cmp(self.item, other)

class ListSet:
    """ListSet is a sorted set for comparable items.  It is inspired by the
    Java Standard Library's TreeSet.  However, it is implemented by a sorted
    list.  This implementation is much slower than a balanced binary tree, but
    has the distinct advantage that I can actually implement it.
    
    The methods of ListSet are all drawn directly from Python's set API,
    Python's list API, and Java's SortedSet API.
    """
    def __init__(self, seq=[]):
        L = list(seq)
        if len(L) > 1:
            L.sort()
            L = kill_dupes(L)
        self._list = L

    def __and__(self, someset):
        if someset.__class__ == self.__class__:
            L = merge_and(self._list, someset._list)
        else:
            L = []
            for x in self._list:
                if x in someset:
                    L.append(x)
        a = ListSet()
        a._list = L
        return a
    
    def __contains__(self, item):
        if len(self._list) == 0:
            return False
        if self._list[0] <= item <= self._list[-1]:
            a = bisect.bisect_left(self._list, item)
            return item == self._list[a]
        else:
            return False
    
    def __eq__(self, someset):
        if someset.__class__ == self.__class__:
            return self._list == someset._list
        else:
            return len(self.symmetric_difference(someset)) == 0
    
    def __ge__(self, someset):
        if someset.__class__ == self.__class__:
            return len(merge_or(self._list, someset._list)) == len(self._list)
        else:
            a = len(someset)
            k = 0
            for i in self._list:
                if i in someset:
                    k += 1
            return k == a
    
    def __gt__(self, someset):
        return (len(self) > len(someset)) and (self >= someset)

    def __iand__(self, someset):
        if someset.__class__ == self.__class__:
            self._list = merge_and(self._list, someset._list)
        else:
            L = []
            for i in self._list:
                if i in someset:
                    L.append(i)
            self._list = L
        return self
    
    def __ior__(self, someset):
        if someset.__class__ == self.__class__:
            self._list = merge_or(self._list, someset._list)
        else:
            self.update(someset)
        return self
    
    def __isub__(self, someset):
        if someset.__class__ == self.__class__:
            self._list = merge_sub(self._list, someset._list)
        else:
            L = []
            for i in self._list:
                if i not in someset:
                    L.append(i)
            self._list = L
        return self
    
    def __iter__(self):
        return self._list.__iter__()
    
    def __ixor__(self, someset):
        if someset.__class__ == self.__class__:
            self._list = merge_xor(self._list, someset._list)
        else:
            self.symmetric_difference_update(someset)
        return self
    
    def __le__(self, someset):
        if someset.__class__ == self.__class__:
            return len(merge_or(self._list, someset._list)) == len(someset._list)
        else:
            for i in self._list:
                if i not in someset:
                   return False
            return True
    
    def __lt__(self, someset):
        return (len(self) < len(someset)) and (self <= someset)
    
    def __ne__(self, someset):
        return not (self == someset)
    
    def __len__(self):
        return len(self._list)
    
    def __or__(self, someset):
        a = ListSet()
        if someset.__class__ == self.__class__:
            a._list = merge_or(self._list, someset._list)
        else:
            a._list = self._list
            a.update(someset)
        return a
    
    __rand__ = __and__
    
    def __repr__(self):
        return "ListSet(" + repr(self._list) +")"
    
    __ror__ = __or__
    
    def __rsub__(self, someset):
        if someset.__class__ == self.__class__:
            a = ListSet()
            a._list = merge_sub(someset._list, self._list)
        else:
            a = ListSet(someset)
            a._list = merge_sub(a._list, self._list)
        return a
    
    def __sub__(self, someset):
        a = ListSet()
        if someset.__class__ == self.__class__:
            a._list = merge_sub(self._list, someset._list)
        else:
            L = []
            for i in self._list:
                if i not in someset:
                    L.append(i)
            a._list = L
        return a
    
    def __xor__(self, someset):
        if someset.__class__ == self.__class__:
            a = ListSet()
            a._list = merge_xor(self._list, someset._list)
        else:
            a = self.symmetric_difference(someset)
        return a
    
    __rxor__ = __xor__
    
    def add(self, item):
        if (len(self._list) > 0) and (item <= self._list[-1]):
            a = bisect.bisect_left(self._list, item)
            if self._list[a] != item:
                self._list.insert(a, item)
        else:
            self._list.append(item)
    
    def clear(self):
        self._list = []
    
    def copy(self):
        a = ListSet()
        a._list = list(self._list) #shallow copy
        return a
    
    def difference(self, iterable):
        L = list(iterable)
        L.sort()
        a = ListSet()
        a._list = merge_sub(self._list, kill_dupes(L))
        return a
    
    def difference_update(self, iterable):
        L = list(iterable)
        L.sort()
        self._list = merge_sub(self._list, kill_dupes(L))
    
    def discard(self, item):
        if (len(self._list) > 0) and (item <= self._list[-1]):
            a = bisect.bisect_left(self._list, item)
            if self._list[a] == item:
                self._list.remove(a)
    
    def intersection(self, iterable):
        L = list(iterable)
        L.sort()
        a = ListSet()
        a._list = merge_and(self._list, kill_dupes(L))
    
    def intersection_update(self, iterable):
        L = list(iterable)
        L.sort()
        self._list = merge_and(self._list, kill_dupes(L))
    
    def issuperset(self, iterable):
        L = list(iterable)
        L.sort()
        m = merge_or(self._list, kill_dupes(L))
        return len(m) == len(self._list)
    
    def issubset(self, iterable):
        L = list(iterable)
        L.sort()
        L = kill_dupes(L)
        m = merge_or(self._list, L)
        return len(m) == len(L)
    
    def pop(self, i = None):
        if i == None:
            return self._list.pop()
        else:
            return self._list.pop(i)
        
    def remove(self, item):
        if (len(self._list) > 0) and (item <= self._list[-1]):
            a = bisect.bisect_left(self._list, item)
            if self._list[a] == item:
                self._list.remove(a)
                return
        raise KeyError("Item is not in the set")
    
    def symmetric_difference(self, iterable):
        L = list(iterable)
        L.sort()
        a = ListSet()
        a._list = merge_xor(self._list, kill_dupes(L))
        return a
    
    def symmetric_difference_update(self, iterable):
        L = list(iterable)
        L.sort()
        self._list = merge_xor(self._list, kill_dupes(L))
    
    def union(self, iterable):
        L = list(iterable)
        L.sort()
        a = ListSet()
        a._list = merge_or(self._list, kill_dupes(L))
    
    def update(self, iterable):
        L = list(iterable)
        L.sort()
        self._list = merge_or(self._list, kill_dupes(L))
    
    def __getitem__(self, key):
        if type(key) == int:
            return self._list.__getitem__(key)
        elif type(key) == slice:
            a = ListSet()
            L = self._list.__getitem__(key)
            if key.step < 0:
                L.reverse()
            a._list = L
            return a
    
    def __delitem__(self, key):
        self._list.__delitem__(key)
    
    def index(self, x, i=0, j=-1):
        if (len(self._list) > 0) and (x <= self._list[-1]):
            a = bisect.bisect_left(self._list, x, i, j)
            if self._list[a] == x:
                return a
        raise ValueError("Item not found")
    
    def position(self, x, i=0, j=-1):
        return bisect.bisect_left(self._list, x, i, j)
    
    def subset(self, x, y):
        a = bisect.bisect_left(self._list, x)
        b = bisect.bisect_left(self._list, y)
        s = ListSet()
        s._list = self._list[a:b]
        return s
    
    def first(self):
        return self._list[0]
    
    def last(self):
        return self._list[-1]
    
    def headset(self, x):
        a = bisect.bisect_left(self._list, x, i, j)
        return self[:a]
    
    def tailset(self, x):
        a = bisect.bisect_left(self._list, x, i, j)
        return self[a:]