Package Anomos :: Module bitfield
[hide private]
[frames] | no frames]

Source Code for Module Anomos.bitfield

 1  # This program is free software: you can redistribute it and/or modify 
 2  # it under the terms of the GNU General Public License as published by 
 3  # the Free Software Foundation, either version 3 of the License, or 
 4  # (at your option) any later version. 
 5  # 
 6  # This program is distributed in the hope that it will be useful, 
 7  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 8  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 9  # GNU General Public License for more details. 
10  # 
11  # You should have received a copy of the GNU General Public License 
12  # along with this program.  If not, see <http://www.gnu.org/licenses/>. 
13   
14  # Written by Bram Cohen, Uoti Urpala, and John Hoffman 
15   
16  from array import array 
17   
18  counts = [chr(sum([(i >> j) & 1 for j in xrange(8)])) for i in xrange(256)] 
19  counts = ''.join(counts) 
20   
21   
22 -class Bitfield:
23
24 - def __init__(self, length, bitstring=None):
25 self.length = length 26 rlen, extra = divmod(length, 8) 27 if bitstring is None: 28 self.numfalse = length 29 if extra: 30 self.bits = array('B', chr(0) * (rlen + 1)) 31 else: 32 self.bits = array('B', chr(0) * rlen) 33 else: 34 if extra: 35 if len(bitstring) != rlen + 1: 36 raise ValueError 37 if (ord(bitstring[-1]) << extra) & 0xFF != 0: 38 raise ValueError 39 else: 40 if len(bitstring) != rlen: 41 raise ValueError 42 c = counts 43 self.numfalse = length - sum(array('B', 44 bitstring.translate(counts))) 45 if self.numfalse != 0: 46 self.bits = array('B', bitstring) 47 else: 48 self.bits = None
49
50 - def __setitem__(self, index, val):
51 assert val 52 pos = index >> 3 53 mask = 128 >> (index & 7) 54 if self.bits[pos] & mask: 55 return 56 self.bits[pos] |= mask 57 self.numfalse -= 1 58 if self.numfalse == 0: 59 self.bits = None
60
61 - def __getitem__(self, index):
62 bits = self.bits 63 if bits is None: 64 return 1 65 return bits[index >> 3] & 128 >> (index & 7)
66
67 - def __len__(self):
68 return self.length
69
70 - def tostring(self):
71 if self.bits is None: 72 rlen, extra = divmod(self.length, 8) 73 r = chr(0xFF) * rlen 74 if extra: 75 r += chr((0xFF << (8 - extra)) & 0xFF) 76 return r 77 else: 78 return self.bits.tostring()
79