bitmask.html


001| '''Bit Mask - arbitrary-length bytes of bits.
001| 
001| Classes:
001|     bitmask         -a bitmask class
001| 
001| '''

002| ####################################################################################################
003| from sys import argv
004| ####################################################################################################
005| BasePath = r'C:\CJS\prj\Python\ws'
006| 
007| BitTest = lambda value: 1 if bool(value) else 0
008| BitStr = lambda value: '1' if bool(value) else '0'
009| 
010| NumberOfBytes = lambda n_bits: int(1 + ((n_bits - 1) // 8))
011| 
012| typename = lambda obj: type(obj).__name__
013| 
014| 
015| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
016| class bitmask:
017|     '''A bitmask class.'''
018|     bytemasks = [pow(2,ix) for ix in range(8)]
019| 
020|     def __init__ (self, length, sep='.'):
021|         '''New bitmask instance.'''
022|         self._nbr_of_bits = length
023|         self._nbr_of_bytes = NumberOfBytes(length)
024|         self._extra_bits = (self._nbr_of_bytes * 8) - self._nbr_of_bits
025|         self._full_mask = pow(2,self._nbr_of_bits) - 1
026|         self.bits = bytearray(self._nbr_of_bytes)
027|         self.sep = sep
028| 
029|     def clear (self):
030|         '''Set all bits in mask to zero. Return self.'''
031|         self.bits = bytearray(self._nbr_of_bytes)
032|         return self
033| 
034|     def ones (self):
035|         '''Set all bits in mask to one. Return self.'''
036|         #ATTN: sets extra bits!
037|         self.bits = bytearray([255]*self._nbr_of_bytes)
038|         return self
039| 
040|     @classmethod
041|     def from_integer (cls, n, length=None):
042|         '''Create bitmask from integer value.'''
043|         n_bits = n.bit_length()
044|         n_byts = NumberOfBytes(n_bits)
045|         # If a length was provided...
046|         if length is not None:
047|             # Check it for sanity...
048|             if length < n_bits:
049|                 raise ValueError(f'Specified length is too small. ({length} < {n_bits})')
050|             n_bits = length
051|             # Possibly expand the byte count...
052|             nb = NumberOfBytes(length)
053|             if n_byts < nb:
054|                 n_byts = nb
055|         # Create new bitmask instance...
056|         bm = cls(n_bits)
057|         bm.bits = n.to_bytes(n_byts, byteorder='big')
058|         return bm
059| 
060|     def __str__ (self):
061|         '''Return bits as a nice string.'''
062|         out = [BitStr(bit) for bit in self]
063|         if self.sep:
064|             divs = list(range(8, self._nbr_of_bits, 8))
065|             for div in reversed(divs):
066|                 out[-div:-div] = self.sep
067|         return ''.join(out)
068| 
069|     def __repr__ (self):
070|         '''Return a debug string.'''
071|         return f'<{typename(self)} {len(self)} @{id(self):08x}>'
072| 
073|     @property
074|     def maxval (self):
075|         return self._full_mask
076| 
077|     # ============ Conversion Methods ============
078|     def __bool__ (self):
079|         '''Return True if all bits zero.'''
080|         return (0 < sum(self.bits))
081| 
082|     def __bytes__ (self):
083|         '''Return bitmask as bytes.'''
084|         return bytes(self.bits)
085| 
086|     def __int__ (self):
087|         '''Return bitmask as an integer.'''
088|         return int.from_bytes(bytes(self), byteorder='big')
089| 
090| 
091|     # ============ Iteration Methods ============
092|     def __len__ (self):
093|         '''Return number of  bytes in bitmask.'''
094|         return self._nbr_of_bits
095| 
096|     def __iter__ (self):
097|         '''Return a byte iterator over bitmask.'''
098|         trim = self._extra_bits
099|         for byt in self.bits:
100|             for m in reversed(self.bytemasks):
101|                 if trim:
102|                     trim -= 1
103|                 else:
104|                     yield BitTest(byt & m)
105| 
106|     def __reversed__ (self):
107|         '''Return a reverse iterator over the bitmask.'''
108|         counter = 0
109|         for byt in reversed(self.bits):
110|             for m in self.bytemasks:
111|                 if self._nbr_of_bits <= counter:
112|                     return
113|                 yield BitTest(byt & m)
114|                 counter += 1
115| 
116|     # ============ Index Operators ============
117|     def _index_value_check (self, ix):
118|         '''Ensure the index is appropriate. Return useful stuff.'''
119|         # Index must be in range...
120|         if self._nbr_of_bits <= abs(ix):
121|             raise IndexError(f'Bit index is out of range. ({ix})')
122|         # Figure out byte and bit indexes...
123|         if ix < 0:
124|             ix += self._nbr_of_bits
125|         which_byte, which_bit = divmod(ix, 8)
126|         bx = self._nbr_of_bytes - which_byte - 1
127|         bm = self.bytemasks[which_bit]
128|         # Return byte index and mask...
129|         return (bx, bm)
130| 
131|     def __getitem__ (self, ix):
132|         '''Get a single bit. Returns zero or one.'''
133|         if isinstance(ix, int):
134|             bx,bm = self._index_value_check(ix)
135|             # Return the bit from the byte...
136|             return BitTest(self.bits[bx] & bm)
137|         if isinstance(ix, slice):
138|             out = []
139|             start = 0 if ix.start is None else ix.start
140|             stop = self._nbr_of_bits if ix.stop is None else ix.stop
141|             step = 1 if ix.step is None else ix.step
142|             for xx in range(start, stop, step):
143|                 out.append(self[xx])
144|             return out
145|         # Unknown index type...
146|         raise IndexError(f'Unknown index type: {ix}')
147| 
148|     def __setitem__ (self, ix, val):
149|         '''Set a single bit. (Note: Expensive operation!)'''
150|         if isinstance(ix, int):
151|             bx,bm = self._index_value_check(ix)
152|             # Get the byte...
153|             byt = self.bits[bx]
154|             # Set the bit per value...
155|             if BitTest(val):
156|                 byt |= bm
157|             else:
158|                 byt &= ~bm
159|             # Rewrite the byte...
160|             self.bits[bx] = byt
161|             return self
162|         #ATTN: Slices not supported.
163|         # Unknown index type...
164|         raise IndexError(f'Unknown index type: {ix}')
165| 
166|     def __delitem__ (self, ix):
167|         '''Delete a bit (not allowed).'''
168|         raise NotImplementedError('Bits may not be deleted.')
169| 
170| 
171|     # ============ Equality Operators ============
172|     #ATTN: Possible issue with extra bits!
173|     def _other_type_check (self, other):
174|         '''Ensure that other is the same type.'''
175|         if not isinstance(other, type(self)):
176|             raise TypeError(f'Expected a {typename(self)} not a {typename(other)}')
177| 
178|     def __eq__ (self, other):
179|         '''Called for obj1==obj2. Return a boolean.'''
180|         self._other_type_check(other)
181|         return self.bits == other.bits
182| 
183|     def __ne__ (self, other):
184|         '''Called for obj1!=obj2. Return a boolean.'''
185|         self._other_type_check(other)
186|         return self.bits != other.bits
187| 
188|     #NOTE: Done automagically because we define __eq__
189|     __hash__ = None
190| 
191|     # ============ Bitwise Operators (AND, OR, XOR) ============
192|     #ATTN: Possible issue with extra bits!
193|     def _other_size_check (self, other):
194|         '''Ensure that other has same size bitmask.'''
195|         if len(self) != len(other):
196|             raise ValueError(f'Bitmasks are different sizes. ({len(self)} != {len(other)})')
197| 
198|     def __and__ (self, other):
199|         '''AND self with another bitmask. Return new bitmask.'''
200|         self._other_type_check(other)
201|         self._other_size_check(other)
202|         # Create and return new instance...
203|         bm = self.__class__(self._nbr_of_bits)
204|         bm.bits = bytearray([(a&b) for a,b in zip(self.bits,other.bits)])
205|         return bm
206| 
207|     def __or__ (self, other):
208|         '''OR self with another bitmask. Return new bitmask.'''
209|         self._other_type_check(other)
210|         self._other_size_check(other)
211|         # Create and return new instance...
212|         bm = self.__class__(self._nbr_of_bits)
213|         bm.bits = bytearray([(a|b) for a,b in zip(self.bits,other.bits)])
214|         return bm
215| 
216|     def __xor__ (self, other):
217|         '''XOR self with another bitmask. Return new bitmask.'''
218|         self._other_type_check(other)
219|         self._other_size_check(other)
220|         # Create and return new instance...
221|         bm = self.__class__(self._nbr_of_bits)
222|         bm.bits = bytearray([(a^b) for a,b in zip(self.bits,other.bits)])
223|         return bm
224| 
225|     __rand__ = __and__
226|     __ror__ = __or__
227|     __rxor__ = __xor__
228| 
229|     def __iand__ (self, other):
230|         '''AND another bitmask with self. Return self.'''
231|         self._other_type_check(other)
232|         self._other_size_check(other)
233|         self.bits = bytearray([(a&b) for a,b in zip(self.bits,other.bits)])
234|         return self
235| 
236|     def __ior__ (self, other):
237|         '''AND another bitmask with self. Return self.'''
238|         self._other_type_check(other)
239|         self._other_size_check(other)
240|         self.bits = bytearray([(a|b) for a,b in zip(self.bits,other.bits)])
241|         return self
242| 
243|     def __ixor__ (self, other):
244|         '''AND another bitmask with self. Return self.'''
245|         self._other_type_check(other)
246|         self._other_size_check(other)
247|         self.bits = bytearray([(a^b) for a,b in zip(self.bits,other.bits)])
248|         return self
249| 
250|     # ============ Shift Operators ============
251|     def _shift_value_check (self, n):
252|         '''Ensure that N is a positive integer.'''
253|         if not isinstance(n, int):
254|             raise ValueError(f'Shift value must be an integer. ({typename(n)})')
255|         if n < 1:
256|             raise ValueError(f'Shift value must be positive. ({n})')
257|         if self._nbr_of_bits < n:
258|             raise ValueError(f'Shift value is out of range. ({n})')
259| 
260|     def __lshift__ (self, n):
261|         '''Shift N bits to left. Return new bitmask.'''
262|         self._shift_value_check(n)
263|         # Convert bitmask to an integer and do bit shift...
264|         val = self._full_mask & (int(self) << n)
265|         # Create and return new instance...
266|         return self.__class__.from_integer(val, length=self._nbr_of_bits)
267| 
268|     def __rshift__ (self, n):
269|         '''Shift N bits to right. Return new bitmask.'''
270|         self._shift_value_check(n)
271|         # Convert bitmask to an integer and do bit shift...
272|         val = int(self) >> n
273|         # Create and return new instance...
274|         return self.__class__.from_integer(val, length=self._nbr_of_bits)
275| 
276|     #ATTN: Probably an error if actually called?
277|     __rlshift__ = __lshift__
278|     __rrshift__ = __rshift__
279| 
280|     def __ilshift__ (self, n):
281|         '''Shift self N bits to left. Return self.'''
282|         self._shift_value_check(n)
283|         # Convert bitmask to an integer and do bit shift...
284|         val = self._full_mask & (int(self) << n)
285|         # Convert shifted integer to bits...
286|         self.bits = val.to_bytes(self._nbr_of_bytes, byteorder='big')
287|         return self
288| 
289|     def __irshift__ (self, n):
290|         '''Shift self N bits to right. Return self.'''
291|         self._shift_value_check(n)
292|         # Convert bitmask to an integer and do bit shift...
293|         val = int(self) >> n
294|         # Convert shifted integer to bits...
295|         self.bits = val.to_bytes(self._nbr_of_bytes, byteorder='big')
296|         return self
297| 
298| 
299| 
300| ##================================================================================================##
301| def main (*args):
302|     bm0 = bitmask(32)
303|     bm1 = bitmask(32)
304|     bm2 = bitmask(100)
305| 
306|     bm1[0] = 1
307|     bm1[1] = 1
308|     bm1[8] = 1
309| 
310|     bm2[ 0] = 1
311|     bm2[50] = 1
312|     bm2[99] = 1
313| 
314|     print(f'{bm1!r}')
315|     print(f'{bm2!r}')
316|     print()
317| 
318|     print(bytes(bm1))
319|     print(int(bm1))
320|     print(bool(bm1))
321|     print(str(bm1))
322|     print()
323| 
324|     print(bytes(bm2))
325|     print(int(bm2))
326|     print(bool(bm2))
327|     print(str(bm2))
328|     print()
329| 
330|     return (bm0, bm1, bm2)
331| 
332| ####################################################################################################
333| if __name__ == '__main__':
334|     print(argv[0])
335|     print()
336|     bm0,bm1,bm2 = main(*argv[1:])
337|     print()
338| ####################################################################################################
339| '''eof'''
340|