~bzr-pqm/bzr/bzr.dev

« 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:
61
61
    """
62
62
    # __slots__ = ['_val']
63
63
 
64
 
    def __init__(self, values=None):
 
64
    def __init__(self, values=None, bitmask=0L):
65
65
        """Create a new intset.
66
66
 
67
67
        values
68
68
            If specified, an initial collection of values.
69
69
        """
70
 
        self._val = 0
 
70
        self._val = bitmask
71
71
        if values != None:
72
72
            self.update(values)
73
73
 
84
84
        return bool(self._val)
85
85
 
86
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
 
87
132
    def __eq__(self, other):
88
 
        """Comparison."""
 
133
        """Comparison.
 
134
 
 
135
        >>> IntSet(range(3)) == IntSet([2, 0, 1])
 
136
        True
 
137
        """
89
138
        if isinstance(other, IntSet):
90
139
            return self._val == other._val
91
140
        else: