/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/intset.py

  • Committer: Martin Pool
  • Date: 2005-07-17 18:06:38 UTC
  • Revision ID: mbp@sourcefrog.net-20050717180638-07ccf05e08276f16
- add len, and, or methods for intset

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/python
 
2
 
 
3
# Copyright (C) 2005 Canonical Ltd
 
4
 
 
5
# This program is free software; you can redistribute it and/or modify
 
6
# it under the terms of the GNU General Public License as published by
 
7
# the Free Software Foundation; either version 2 of the License, or
 
8
# (at your option) any later version.
 
9
 
 
10
# This program is distributed in the hope that it will be useful,
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
# GNU General Public License for more details.
 
14
 
 
15
# You should have received a copy of the GNU General Public License
 
16
# along with this program; if not, write to the Free Software
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
18
 
 
19
# Author: Martin Pool <mbp@canonical.com>
 
20
 
 
21
 
 
22
class IntSet(Exception):
 
23
    """Faster set-like class storing only whole numbers.
 
24
 
 
25
    Despite the name this stores long integers happily, but negative
 
26
    values are not allowed.
 
27
 
 
28
    >>> a = IntSet([0, 2, 5])
 
29
    >>> bool(a)
 
30
    True
 
31
    >>> 2 in a
 
32
    True
 
33
    >>> 4 in a
 
34
    False
 
35
    >>> a.add(4)
 
36
    >>> 4 in a
 
37
    True
 
38
 
 
39
    >>> b = IntSet()
 
40
    >>> not b
 
41
    True
 
42
    >>> b.add(10)
 
43
    >>> 10 in a
 
44
    False
 
45
    >>> a.update(b)
 
46
    >>> 10 in a
 
47
    True
 
48
    >>> a.update(range(5))
 
49
    >>> 3 in a
 
50
    True
 
51
 
 
52
    Being a set, duplicates are ignored:
 
53
    >>> a = IntSet()
 
54
    >>> a.add(10)
 
55
    >>> a.add(10)
 
56
    >>> 10 in a
 
57
    True
 
58
    >>> list(a)
 
59
    [10]
 
60
    
 
61
    """
 
62
    # __slots__ = ['_val']
 
63
 
 
64
    def __init__(self, values=None, bitmask=0L):
 
65
        """Create a new intset.
 
66
 
 
67
        values
 
68
            If specified, an initial collection of values.
 
69
        """
 
70
        self._val = bitmask
 
71
        if values != None:
 
72
            self.update(values)
 
73
 
 
74
 
 
75
    def __nonzero__(self):
 
76
        """IntSets are false if empty, otherwise True.
 
77
 
 
78
        >>> bool(IntSet())
 
79
        False
 
80
        
 
81
        >>> bool(IntSet([0]))
 
82
        True
 
83
        """
 
84
        return bool(self._val)
 
85
 
 
86
 
 
87
    def __len__(self):
 
88
        """Number of elements in set.
 
89
 
 
90
        >>> len(IntSet(xrange(20000)))
 
91
        20000
 
92
        """
 
93
        v = self._val
 
94
        c = 0
 
95
        while v:
 
96
            if v & 1:
 
97
                c += 1
 
98
            v = v >> 1
 
99
        return c
 
100
 
 
101
 
 
102
    def __and__(self, other):
 
103
        """Set intersection.
 
104
 
 
105
        >>> a = IntSet(range(10))
 
106
        >>> len(a)
 
107
        10
 
108
        >>> b = a & a
 
109
        >>> b == a
 
110
        True
 
111
        >>> a = a & IntSet([5, 7, 11, 13])
 
112
        >>> list(a)
 
113
        [5, 7]
 
114
        """
 
115
        if not isinstance(other, IntSet):
 
116
            raise NotImplementedError(type(other))
 
117
        return IntSet(bitmask=(self._val & other._val))
 
118
 
 
119
 
 
120
    def __or__(self, other):
 
121
        """Set union.
 
122
 
 
123
        >>> a = IntSet(range(10)) | IntSet([5, 15, 25])
 
124
        >>> len(a)
 
125
        12
 
126
        """
 
127
        if not isinstance(other, IntSet):
 
128
            raise NotImplementedError(type(other))
 
129
        return IntSet(bitmask=(self._val | other._val))        
 
130
 
 
131
 
 
132
    def __eq__(self, other):
 
133
        """Comparison.
 
134
 
 
135
        >>> IntSet(range(3)) == IntSet([2, 0, 1])
 
136
        True
 
137
        """
 
138
        if isinstance(other, IntSet):
 
139
            return self._val == other._val
 
140
        else:
 
141
            return False
 
142
 
 
143
 
 
144
    def __ne__(self, other):
 
145
        return not self.__eq__(other)
 
146
 
 
147
 
 
148
    def __contains__(self, i):
 
149
        assert i >= 0
 
150
        return self._val & (1L << i)
 
151
 
 
152
 
 
153
    def __iter__(self):
 
154
        """Return contents of set.
 
155
 
 
156
        >>> list(IntSet())
 
157
        []
 
158
        >>> list(IntSet([0, 1, 5, 7]))
 
159
        [0, 1, 5, 7]
 
160
        """
 
161
        v = self._val
 
162
        o = 0
 
163
        # XXX: This is a bit slow
 
164
        while v:
 
165
            if v & 1:
 
166
                yield o
 
167
            v = v >> 1
 
168
            o = o + 1
 
169
 
 
170
        
 
171
    def update(self, to_add):
 
172
        """Add all the values from the sequence or intset to_add"""
 
173
        if isinstance(to_add, IntSet):
 
174
            self._val |= to_add._val
 
175
        else:
 
176
            for i in to_add:
 
177
                assert i >= 0
 
178
                self._val |= (1L << i)
 
179
 
 
180
 
 
181
    def add(self, to_add):
 
182
        assert 0 <= to_add
 
183
        self._val |= (1L << to_add)
 
184
 
 
185
 
 
186
    def remove(self, to_remove):
 
187
        """Remove one value from the set.
 
188
 
 
189
        Raises KeyError if the value is not present.
 
190
 
 
191
        >>> a = IntSet([10])
 
192
        >>> a.remove(9)
 
193
        Traceback (most recent call last):
 
194
          File "/usr/lib/python2.4/doctest.py", line 1243, in __run
 
195
            compileflags, 1) in test.globs
 
196
          File "<doctest __main__.IntSet.remove[1]>", line 1, in ?
 
197
            a.remove(9)
 
198
        KeyError: 9
 
199
        >>> a.remove(10)
 
200
        >>> not a
 
201
        True
 
202
        """
 
203
        assert 0 <= to_remove
 
204
        m = 1L << to_remove
 
205
        if not self._val & m:
 
206
            raise KeyError(to_remove)
 
207
        self._val ^= m
 
208
        
 
209
        
 
210
            
 
211
    
 
212
 
 
213
if __name__ == '__main__':
 
214
    import doctest
 
215
    doctest.testmod()
 
216