Belle II Software  release-05-02-19
bitstring.py
1 #!/usr/bin/env python
2 """
3 This package defines classes that simplify bit-wise creation, manipulation and
4 interpretation of data.
5 
6 Classes:
7 
8 Bits -- An immutable container for binary data.
9 BitArray -- A mutable container for binary data.
10 ConstBitStream -- An immutable container with streaming methods.
11 BitStream -- A mutable container with streaming methods.
12 
13  Bits (base class)
14  / \
15  + mutating methods / \ + streaming methods
16  / \
17  BitArray ConstBitStream
18  \ /
19  \ /
20  \ /
21  BitStream
22 
23 Functions:
24 
25 pack -- Create a BitStream from a format string.
26 
27 Exceptions:
28 
29 Error -- Module exception base class.
30 CreationError -- Error during creation.
31 InterpretError -- Inappropriate interpretation of binary data.
32 ByteAlignError -- Whole byte position or length needed.
33 ReadError -- Reading or peeking past the end of a bitstring.
34 
35 https://github.com/scott-griffiths/bitstring
36 """
37 
38 __licence__ = """
39 The MIT License
40 
41 Copyright (c) 2006-2016 Scott Griffiths (dr.scottgriffiths@gmail.com)
42 
43 Permission is hereby granted, free of charge, to any person obtaining a copy
44 of this software and associated documentation files (the "Software"), to deal
45 in the Software without restriction, including without limitation the rights
46 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
47 copies of the Software, and to permit persons to whom the Software is
48 furnished to do so, subject to the following conditions:
49 
50 The above copyright notice and this permission notice shall be included in
51 all copies or substantial portions of the Software.
52 
53 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
54 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
55 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
56 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
57 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
58 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
59 THE SOFTWARE.
60 """
61 
62 __version__ = "3.1.5"
63 
64 __author__ = "Scott Griffiths"
65 
66 import numbers
67 import copy
68 import sys
69 import re
70 import binascii
71 import mmap
72 import os
73 import struct
74 import operator
75 import collections
76 import array
77 
78 byteorder = sys.byteorder
79 
80 bytealigned = False
81 """Determines whether a number of methods default to working only on byte boundaries."""
82 
83 # Maximum number of digits to use in __str__ and __repr__.
84 MAX_CHARS = 250
85 
86 # Maximum size of caches used for speed optimisations.
87 CACHE_SIZE = 1000
88 
89 
90 class Error(Exception):
91  """Base class for errors in the bitstring module."""
92 
93  def __init__(self, *params):
94  self.msg = params[0] if params else ''
95  self.params = params[1:]
96 
97  def __str__(self):
98  if self.params:
99  return self.msg.format(*self.params)
100  return self.msg
101 
102 
103 class ReadError(Error, IndexError):
104  """Reading or peeking past the end of a bitstring."""
105 
106  def __init__(self, *params):
107  Error.__init__(self, *params)
108 
109 
110 class InterpretError(Error, ValueError):
111  """Inappropriate interpretation of binary data."""
112 
113  def __init__(self, *params):
114  Error.__init__(self, *params)
115 
116 
118  """Whole-byte position or length needed."""
119 
120  def __init__(self, *params):
121  Error.__init__(self, *params)
122 
123 
124 class CreationError(Error, ValueError):
125  """Inappropriate argument during bitstring creation."""
126 
127  def __init__(self, *params):
128  Error.__init__(self, *params)
129 
130 
131 class ConstByteStore(object):
132  """Stores raw bytes together with a bit offset and length.
133 
134  Used internally - not part of public interface.
135  """
136 
137  __slots__ = ('offset', '_rawarray', 'bitlength')
138 
139  def __init__(self, data, bitlength=None, offset=None):
140  """data is either a bytearray or a MmapByteArray"""
141  self._rawarray = data
142  if offset is None:
143  offset = 0
144  if bitlength is None:
145  bitlength = 8 * len(data) - offset
146  self.offset = offset
147  self.bitlength = bitlength
148 
149  def getbit(self, pos):
150  assert 0 <= pos < self.bitlength
151  byte, bit = divmod(self.offset + pos, 8)
152  return bool(self._rawarray[byte] & (128 >> bit))
153 
154  def getbyte(self, pos):
155  """Direct access to byte data."""
156  return self._rawarray[pos]
157 
158  def getbyteslice(self, start, end):
159  """Direct access to byte data."""
160  c = self._rawarray[start:end]
161  return c
162 
163  @property
164  def bytelength(self):
165  if not self.bitlength:
166  return 0
167  sb = self.offset // 8
168  eb = (self.offset + self.bitlength - 1) // 8
169  return eb - sb + 1
170 
171  def __copy__(self):
172  return ByteStore(self._rawarray[:], self.bitlength, self.offset)
173 
174  def _appendstore(self, store):
175  """Join another store on to the end of this one."""
176  if not store.bitlength:
177  return
178  # Set new array offset to the number of bits in the final byte of current array.
179  store = offsetcopy(store, (self.offset + self.bitlength) % 8)
180  if store.offset:
181  # first do the byte with the join.
182  joinval = (self._rawarray.pop() & (255 ^ (255 >> store.offset)) |
183  (store.getbyte(0) & (255 >> store.offset)))
184  self._rawarray.append(joinval)
185  self._rawarray.extend(store._rawarray[1:])
186  else:
187  self._rawarray.extend(store._rawarray)
188  self.bitlength += store.bitlength
189 
190  def _prependstore(self, store):
191  """Join another store on to the start of this one."""
192  if not store.bitlength:
193  return
194  # Set the offset of copy of store so that it's final byte
195  # ends in a position that matches the offset of self,
196  # then join self on to the end of it.
197  store = offsetcopy(store, (self.offset - store.bitlength) % 8)
198  assert (store.offset + store.bitlength) % 8 == self.offset % 8
199  bit_offset = self.offset % 8
200  if bit_offset:
201  # first do the byte with the join.
202  store.setbyte(-1, (store.getbyte(-1) & (255 ^ (255 >> bit_offset)) |
203  (self._rawarray[self.byteoffset] & (255 >> bit_offset))))
204  store._rawarray.extend(self._rawarray[self.byteoffset + 1: self.byteoffset + self.bytelength])
205  else:
206  store._rawarray.extend(self._rawarray[self.byteoffset: self.byteoffset + self.bytelength])
207  self._rawarray = store._rawarray
208  self.offset = store.offset
209  self.bitlength += store.bitlength
210 
211  @property
212  def byteoffset(self):
213  return self.offset // 8
214 
215  @property
216  def rawbytes(self):
217  return self._rawarray
218 
219 
221  """Adding mutating methods to ConstByteStore
222 
223  Used internally - not part of public interface.
224  """
225  __slots__ = ()
226 
227  def setbit(self, pos):
228  assert 0 <= pos < self.bitlength
229  byte, bit = divmod(self.offset + pos, 8)
230  self._rawarray[byte] |= (128 >> bit)
231 
232  def unsetbit(self, pos):
233  assert 0 <= pos < self.bitlength
234  byte, bit = divmod(self.offset + pos, 8)
235  self._rawarray[byte] &= ~(128 >> bit)
236 
237  def invertbit(self, pos):
238  assert 0 <= pos < self.bitlength
239  byte, bit = divmod(self.offset + pos, 8)
240  self._rawarray[byte] ^= (128 >> bit)
241 
242  def setbyte(self, pos, value):
243  self._rawarray[pos] = value
244 
245  def setbyteslice(self, start, end, value):
246  self._rawarray[start:end] = value
247 
248 
249 def offsetcopy(s, newoffset):
250  """Return a copy of a ByteStore with the newoffset.
251 
252  Not part of public interface.
253  """
254  assert 0 <= newoffset < 8
255  if not s.bitlength:
256  return copy.copy(s)
257  else:
258  if newoffset == s.offset % 8:
259  return ByteStore(s.getbyteslice(s.byteoffset, s.byteoffset + s.bytelength), s.bitlength, newoffset)
260  newdata = []
261  d = s._rawarray
262  assert newoffset != s.offset % 8
263  if newoffset < s.offset % 8:
264  # We need to shift everything left
265  shiftleft = s.offset % 8 - newoffset
266  # First deal with everything except for the final byte
267  for x in range(s.byteoffset, s.byteoffset + s.bytelength - 1):
268  newdata.append(((d[x] << shiftleft) & 0xff) +
269  (d[x + 1] >> (8 - shiftleft)))
270  bits_in_last_byte = (s.offset + s.bitlength) % 8
271  if not bits_in_last_byte:
272  bits_in_last_byte = 8
273  if bits_in_last_byte > shiftleft:
274  newdata.append((d[s.byteoffset + s.bytelength - 1] << shiftleft) & 0xff)
275  else: # newoffset > s._offset % 8
276  shiftright = newoffset - s.offset % 8
277  newdata.append(s.getbyte(0) >> shiftright)
278  for x in range(s.byteoffset + 1, s.byteoffset + s.bytelength):
279  newdata.append(((d[x - 1] << (8 - shiftright)) & 0xff) +
280  (d[x] >> shiftright))
281  bits_in_last_byte = (s.offset + s.bitlength) % 8
282  if not bits_in_last_byte:
283  bits_in_last_byte = 8
284  if bits_in_last_byte + shiftright > 8:
285  newdata.append((d[s.byteoffset + s.bytelength - 1] << (8 - shiftright)) & 0xff)
286  new_s = ByteStore(bytearray(newdata), s.bitlength, newoffset)
287  assert new_s.offset == newoffset
288  return new_s
289 
290 
291 def equal(a, b):
292  """Return True if ByteStores a == b.
293 
294  Not part of public interface.
295  """
296  # We want to return False for inequality as soon as possible, which
297  # means we get lots of special cases.
298  # First the easy one - compare lengths:
299  a_bitlength = a.bitlength
300  b_bitlength = b.bitlength
301  if a_bitlength != b_bitlength:
302  return False
303  if not a_bitlength:
304  assert b_bitlength == 0
305  return True
306  # Make 'a' the one with the smaller offset
307  if (a.offset % 8) > (b.offset % 8):
308  a, b = b, a
309  # and create some aliases
310  a_bitoff = a.offset % 8
311  b_bitoff = b.offset % 8
312  a_byteoffset = a.byteoffset
313  b_byteoffset = b.byteoffset
314  a_bytelength = a.bytelength
315  b_bytelength = b.bytelength
316  da = a._rawarray
317  db = b._rawarray
318 
319  # If they are pointing to the same data, they must be equal
320  if da is db and a.offset == b.offset:
321  return True
322 
323  if a_bitoff == b_bitoff:
324  bits_spare_in_last_byte = 8 - (a_bitoff + a_bitlength) % 8
325  if bits_spare_in_last_byte == 8:
326  bits_spare_in_last_byte = 0
327  # Special case for a, b contained in a single byte
328  if a_bytelength == 1:
329  a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
330  b_val = ((db[b_byteoffset] << b_bitoff) & 0xff) >> (8 - b_bitlength)
331  return a_val == b_val
332  # Otherwise check first byte
333  if da[a_byteoffset] & (0xff >> a_bitoff) != db[b_byteoffset] & (0xff >> b_bitoff):
334  return False
335  # then everything up to the last
336  b_a_offset = b_byteoffset - a_byteoffset
337  for x in range(1 + a_byteoffset, a_byteoffset + a_bytelength - 1):
338  if da[x] != db[b_a_offset + x]:
339  return False
340  # and finally the last byte
341  return (da[a_byteoffset + a_bytelength - 1] >> bits_spare_in_last_byte ==
342  db[b_byteoffset + b_bytelength - 1] >> bits_spare_in_last_byte)
343 
344  assert a_bitoff != b_bitoff
345  # This is how much we need to shift a to the right to compare with b:
346  shift = b_bitoff - a_bitoff
347  # Special case for b only one byte long
348  if b_bytelength == 1:
349  assert a_bytelength == 1
350  a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
351  b_val = ((db[b_byteoffset] << b_bitoff) & 0xff) >> (8 - b_bitlength)
352  return a_val == b_val
353  # Special case for a only one byte long
354  if a_bytelength == 1:
355  assert b_bytelength == 2
356  a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
357  b_val = ((db[b_byteoffset] << 8) + db[b_byteoffset + 1]) << b_bitoff
358  b_val &= 0xffff
359  b_val >>= 16 - b_bitlength
360  return a_val == b_val
361 
362  # Compare first byte of b with bits from first byte of a
363  if (da[a_byteoffset] & (0xff >> a_bitoff)) >> shift != db[b_byteoffset] & (0xff >> b_bitoff):
364  return False
365  # Now compare every full byte of b with bits from 2 bytes of a
366  for x in range(1, b_bytelength - 1):
367  # Construct byte from 2 bytes in a to compare to byte in b
368  b_val = db[b_byteoffset + x]
369  a_val = ((da[a_byteoffset + x - 1] << 8) + da[a_byteoffset + x]) >> shift
370  a_val &= 0xff
371  if a_val != b_val:
372  return False
373 
374  # Now check bits in final byte of b
375  final_b_bits = (b.offset + b_bitlength) % 8
376  if not final_b_bits:
377  final_b_bits = 8
378  b_val = db[b_byteoffset + b_bytelength - 1] >> (8 - final_b_bits)
379  final_a_bits = (a.offset + a_bitlength) % 8
380  if not final_a_bits:
381  final_a_bits = 8
382  if b.bytelength > a_bytelength:
383  assert b_bytelength == a_bytelength + 1
384  a_val = da[a_byteoffset + a_bytelength - 1] >> (8 - final_a_bits)
385  a_val &= 0xff >> (8 - final_b_bits)
386  return a_val == b_val
387  assert a_bytelength == b_bytelength
388  a_val = da[a_byteoffset + a_bytelength - 2] << 8
389  a_val += da[a_byteoffset + a_bytelength - 1]
390  a_val >>= (8 - final_a_bits)
391  a_val &= 0xff >> (8 - final_b_bits)
392  return a_val == b_val
393 
394 
395 class MmapByteArray(object):
396  """Looks like a bytearray, but from an mmap.
397 
398  Not part of public interface.
399  """
400 
401  __slots__ = ('filemap', 'filelength', 'source', 'byteoffset', 'bytelength')
402 
403  def __init__(self, source, bytelength=None, byteoffset=None):
404  self.source = source
405  source.seek(0, os.SEEK_END)
406  self.filelength = source.tell()
407  if byteoffset is None:
408  byteoffset = 0
409  if bytelength is None:
410  bytelength = self.filelength - byteoffset
411  self.byteoffset = byteoffset
412  self.bytelength = bytelength
413  self.filemap = mmap.mmap(source.fileno(), 0, access=mmap.ACCESS_READ)
414 
415  def __getitem__(self, key):
416  try:
417  start = key.start
418  stop = key.stop
419  except AttributeError:
420  try:
421  assert 0 <= key < self.bytelength
422  return ord(self.filemap[key + self.byteoffset])
423  except TypeError:
424  # for Python 3
425  return self.filemap[key + self.byteoffset]
426  else:
427  if start is None:
428  start = 0
429  if stop is None:
430  stop = self.bytelength
431  assert key.step is None
432  assert 0 <= start < self.bytelength
433  assert 0 <= stop <= self.bytelength
434  s = slice(start + self.byteoffset, stop + self.byteoffset)
435  return bytearray(self.filemap.__getitem__(s))
436 
437  def __len__(self):
438  return self.bytelength
439 
440 
441 # This creates a dictionary for every possible byte with the value being
442 # the key with its bits reversed.
443 BYTE_REVERSAL_DICT = dict()
444 
445 # For Python 2.x/ 3.x coexistence
446 # Yes this is very very hacky.
447 try:
448  xrange
449  for i in range(256):
450  BYTE_REVERSAL_DICT[i] = chr(int("{0:08b}".format(i)[::-1], 2))
451 except NameError:
452  for i in range(256):
453  BYTE_REVERSAL_DICT[i] = bytes([int("{0:08b}".format(i)[::-1], 2)])
454  from io import IOBase as file
455  xrange = range
456  basestring = str
457 
458 # Python 2.x octals start with '0', in Python 3 it's '0o'
459 LEADING_OCT_CHARS = len(oct(1)) - 1
460 
461 
463  """Return string made lowercase and with all whitespace removed."""
464  s = ''.join(s.split()).lower()
465  return s
466 
467 
468 INIT_NAMES = ('uint', 'int', 'ue', 'se', 'sie', 'uie', 'hex', 'oct', 'bin', 'bits',
469  'uintbe', 'intbe', 'uintle', 'intle', 'uintne', 'intne',
470  'float', 'floatbe', 'floatle', 'floatne', 'bytes', 'bool', 'pad')
471 
472 TOKEN_RE = re.compile(r'(?P<name>' + '|'.join(INIT_NAMES) +
473  r')((:(?P<len>[^=]+)))?(=(?P<value>.*))?$', re.IGNORECASE)
474 DEFAULT_UINT = re.compile(r'(?P<len>[^=]+)?(=(?P<value>.*))?$', re.IGNORECASE)
475 
476 MULTIPLICATIVE_RE = re.compile(r'(?P<factor>.*)\*(?P<token>.+)')
477 
478 # Hex, oct or binary literals
479 LITERAL_RE = re.compile(r'(?P<name>0(x|o|b))(?P<value>.+)', re.IGNORECASE)
480 
481 # An endianness indicator followed by one or more struct.pack codes
482 STRUCT_PACK_RE = re.compile(r'(?P<endian><|>|@)?(?P<fmt>(?:\d*[bBhHlLqQfd])+)$')
483 
484 # A number followed by a single character struct.pack code
485 STRUCT_SPLIT_RE = re.compile(r'\d*[bBhHlLqQfd]')
486 
487 # These replicate the struct.pack codes
488 # Big-endian
489 REPLACEMENTS_BE = {'b': 'intbe:8', 'B': 'uintbe:8',
490  'h': 'intbe:16', 'H': 'uintbe:16',
491  'l': 'intbe:32', 'L': 'uintbe:32',
492  'q': 'intbe:64', 'Q': 'uintbe:64',
493  'f': 'floatbe:32', 'd': 'floatbe:64'}
494 # Little-endian
495 REPLACEMENTS_LE = {'b': 'intle:8', 'B': 'uintle:8',
496  'h': 'intle:16', 'H': 'uintle:16',
497  'l': 'intle:32', 'L': 'uintle:32',
498  'q': 'intle:64', 'Q': 'uintle:64',
499  'f': 'floatle:32', 'd': 'floatle:64'}
500 
501 # Size in bytes of all the pack codes.
502 PACK_CODE_SIZE = {'b': 1, 'B': 1, 'h': 2, 'H': 2, 'l': 4, 'L': 4,
503  'q': 8, 'Q': 8, 'f': 4, 'd': 8}
504 
505 _tokenname_to_initialiser = {'hex': 'hex', '0x': 'hex', '0X': 'hex', 'oct': 'oct',
506  '0o': 'oct', '0O': 'oct', 'bin': 'bin', '0b': 'bin',
507  '0B': 'bin', 'bits': 'auto', 'bytes': 'bytes', 'pad': 'pad'}
508 
509 
510 def structparser(token):
511  """Parse struct-like format string token into sub-token list."""
512  m = STRUCT_PACK_RE.match(token)
513  if not m:
514  return [token]
515  else:
516  endian = m.group('endian')
517  if endian is None:
518  return [token]
519  # Split the format string into a list of 'q', '4h' etc.
520  formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt'))
521  # Now deal with mulitiplicative factors, 4h -> hhhh etc.
522  fmt = ''.join([f[-1] * int(f[:-1]) if len(f) != 1 else
523  f for f in formatlist])
524  if endian == '@':
525  # Native endianness
526  if byteorder == 'little':
527  endian = '<'
528  else:
529  assert byteorder == 'big'
530  endian = '>'
531  if endian == '<':
532  tokens = [REPLACEMENTS_LE[c] for c in fmt]
533  else:
534  assert endian == '>'
535  tokens = [REPLACEMENTS_BE[c] for c in fmt]
536  return tokens
537 
538 
539 def tokenparser(fmt, keys=None, token_cache={}):
540  """Divide the format string into tokens and parse them.
541 
542  Return stretchy token and list of [initialiser, length, value]
543  initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc.
544  length is None if not known, as is value.
545 
546  If the token is in the keyword dictionary (keys) then it counts as a
547  special case and isn't messed with.
548 
549  tokens must be of the form: [factor*][initialiser][:][length][=value]
550 
551  """
552  try:
553  return token_cache[(fmt, keys)]
554  except KeyError:
555  token_key = (fmt, keys)
556  # Very inefficient expanding of brackets.
557  fmt = expand_brackets(fmt)
558  # Split tokens by ',' and remove whitespace
559  # The meta_tokens can either be ordinary single tokens or multiple
560  # struct-format token strings.
561  meta_tokens = (''.join(f.split()) for f in fmt.split(','))
562  return_values = []
563  stretchy_token = False
564  for meta_token in meta_tokens:
565  # See if it has a multiplicative factor
566  m = MULTIPLICATIVE_RE.match(meta_token)
567  if not m:
568  factor = 1
569  else:
570  factor = int(m.group('factor'))
571  meta_token = m.group('token')
572  # See if it's a struct-like format
573  tokens = structparser(meta_token)
574  ret_vals = []
575  for token in tokens:
576  if keys and token in keys:
577  # Don't bother parsing it, it's a keyword argument
578  ret_vals.append([token, None, None])
579  continue
580  value = length = None
581  if token == '':
582  continue
583  # Match literal tokens of the form 0x... 0o... and 0b...
584  m = LITERAL_RE.match(token)
585  if m:
586  name = m.group('name')
587  value = m.group('value')
588  ret_vals.append([name, length, value])
589  continue
590  # Match everything else:
591  m1 = TOKEN_RE.match(token)
592  if not m1:
593  # and if you don't specify a 'name' then the default is 'uint':
594  m2 = DEFAULT_UINT.match(token)
595  if not m2:
596  raise ValueError("Don't understand token '{0}'.".format(token))
597  if m1:
598  name = m1.group('name')
599  length = m1.group('len')
600  if m1.group('value'):
601  value = m1.group('value')
602  else:
603  assert m2
604  name = 'uint'
605  length = m2.group('len')
606  if m2.group('value'):
607  value = m2.group('value')
608  if name == 'bool':
609  if length is not None:
610  raise ValueError("You can't specify a length with bool tokens - they are always one bit.")
611  length = 1
612  if length is None and name not in ('se', 'ue', 'sie', 'uie'):
613  stretchy_token = True
614  if length is not None:
615  # Try converting length to int, otherwise check it's a key.
616  try:
617  length = int(length)
618  if length < 0:
619  raise Error
620  # For the 'bytes' token convert length to bits.
621  if name == 'bytes':
622  length *= 8
623  except Error:
624  raise ValueError("Can't read a token with a negative length.")
625  except ValueError:
626  if not keys or length not in keys:
627  raise ValueError("Don't understand length '{0}' of token.".format(length))
628  ret_vals.append([name, length, value])
629  # This multiplies by the multiplicative factor, but this means that
630  # we can't allow keyword values as multipliers (e.g. n*uint:8).
631  # The only way to do this would be to return the factor in some fashion
632  # (we can't use the key's value here as it would mean that we couldn't
633  # sensibly continue to cache the function's results. (TODO).
634  return_values.extend(ret_vals * factor)
635  return_values = [tuple(x) for x in return_values]
636  if len(token_cache) < CACHE_SIZE:
637  token_cache[token_key] = stretchy_token, return_values
638  return stretchy_token, return_values
639 
640 
641 # Looks for first number*(
642 BRACKET_RE = re.compile(r'(?P<factor>\d+)\*\(')
643 
644 
646  """Remove whitespace and expand all brackets."""
647  s = ''.join(s.split())
648  while True:
649  start = s.find('(')
650  if start == -1:
651  break
652  count = 1 # Number of hanging open brackets
653  p = start + 1
654  while p < len(s):
655  if s[p] == '(':
656  count += 1
657  if s[p] == ')':
658  count -= 1
659  if not count:
660  break
661  p += 1
662  if count:
663  raise ValueError("Unbalanced parenthesis in '{0}'.".format(s))
664  if start == 0 or s[start - 1] != '*':
665  s = s[0:start] + s[start + 1:p] + s[p + 1:]
666  else:
667  m = BRACKET_RE.search(s)
668  if m:
669  factor = int(m.group('factor'))
670  matchstart = m.start('factor')
671  s = s[0:matchstart] + (factor - 1) * (s[start + 1:p] + ',') + s[start + 1:p] + s[p + 1:]
672  else:
673  raise ValueError("Failed to parse '{0}'.".format(s))
674  return s
675 
676 
677 # This converts a single octal digit to 3 bits.
678 OCT_TO_BITS = ['{0:03b}'.format(i) for i in xrange(8)]
679 
680 # A dictionary of number of 1 bits contained in binary representation of any byte
681 BIT_COUNT = dict(zip(xrange(256), [bin(i).count('1') for i in xrange(256)]))
682 
683 
684 class Bits(object):
685  """A container holding an immutable sequence of bits.
686 
687  For a mutable container use the BitArray class instead.
688 
689  Methods:
690 
691  all() -- Check if all specified bits are set to 1 or 0.
692  any() -- Check if any of specified bits are set to 1 or 0.
693  count() -- Count the number of bits set to 1 or 0.
694  cut() -- Create generator of constant sized chunks.
695  endswith() -- Return whether the bitstring ends with a sub-string.
696  find() -- Find a sub-bitstring in the current bitstring.
697  findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
698  join() -- Join bitstrings together using current bitstring.
699  rfind() -- Seek backwards to find a sub-bitstring.
700  split() -- Create generator of chunks split by a delimiter.
701  startswith() -- Return whether the bitstring starts with a sub-bitstring.
702  tobytes() -- Return bitstring as bytes, padding if needed.
703  tofile() -- Write bitstring to file, padding if needed.
704  unpack() -- Interpret bits using format string.
705 
706  Special methods:
707 
708  Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^.
709 
710  Properties:
711 
712  bin -- The bitstring as a binary string.
713  bool -- For single bit bitstrings, interpret as True or False.
714  bytes -- The bitstring as a bytes object.
715  float -- Interpret as a floating point number.
716  floatbe -- Interpret as a big-endian floating point number.
717  floatle -- Interpret as a little-endian floating point number.
718  floatne -- Interpret as a native-endian floating point number.
719  hex -- The bitstring as a hexadecimal string.
720  int -- Interpret as a two's complement signed integer.
721  intbe -- Interpret as a big-endian signed integer.
722  intle -- Interpret as a little-endian signed integer.
723  intne -- Interpret as a native-endian signed integer.
724  len -- Length of the bitstring in bits.
725  oct -- The bitstring as an octal string.
726  se -- Interpret as a signed exponential-Golomb code.
727  ue -- Interpret as an unsigned exponential-Golomb code.
728  sie -- Interpret as a signed interleaved exponential-Golomb code.
729  uie -- Interpret as an unsigned interleaved exponential-Golomb code.
730  uint -- Interpret as a two's complement unsigned integer.
731  uintbe -- Interpret as a big-endian unsigned integer.
732  uintle -- Interpret as a little-endian unsigned integer.
733  uintne -- Interpret as a native-endian unsigned integer.
734 
735  """
736 
737  __slots__ = ('_datastore')
738 
739  def __init__(self, auto=None, length=None, offset=None, **kwargs):
740  """Either specify an 'auto' initialiser:
741  auto -- a string of comma separated tokens, an integer, a file object,
742  a bytearray, a boolean iterable, an array or another bitstring.
743 
744  Or initialise via **kwargs with one (and only one) of:
745  bytes -- raw data as a string, for example read from a binary file.
746  bin -- binary string representation, e.g. '0b001010'.
747  hex -- hexadecimal string representation, e.g. '0x2ef'
748  oct -- octal string representation, e.g. '0o777'.
749  uint -- an unsigned integer.
750  int -- a signed integer.
751  float -- a floating point number.
752  uintbe -- an unsigned big-endian whole byte integer.
753  intbe -- a signed big-endian whole byte integer.
754  floatbe - a big-endian floating point number.
755  uintle -- an unsigned little-endian whole byte integer.
756  intle -- a signed little-endian whole byte integer.
757  floatle -- a little-endian floating point number.
758  uintne -- an unsigned native-endian whole byte integer.
759  intne -- a signed native-endian whole byte integer.
760  floatne -- a native-endian floating point number.
761  se -- a signed exponential-Golomb code.
762  ue -- an unsigned exponential-Golomb code.
763  sie -- a signed interleaved exponential-Golomb code.
764  uie -- an unsigned interleaved exponential-Golomb code.
765  bool -- a boolean (True or False).
766  filename -- a file which will be opened in binary read-only mode.
767 
768  Other keyword arguments:
769  length -- length of the bitstring in bits, if needed and appropriate.
770  It must be supplied for all integer and float initialisers.
771  offset -- bit offset to the data. These offset bits are
772  ignored and this is mainly intended for use when
773  initialising using 'bytes' or 'filename'.
774 
775  """
776  pass
777 
778  def __new__(cls, auto=None, length=None, offset=None, _cache={}, **kwargs):
779  # For instances auto-initialised with a string we intern the
780  # instance for re-use.
781  try:
782  if isinstance(auto, basestring):
783  try:
784  return _cache[auto]
785  except KeyError:
786  x = object.__new__(Bits)
787  try:
788  _, tokens = tokenparser(auto)
789  except ValueError as e:
790  raise CreationError(*e.args)
791  x._datastore = ConstByteStore(bytearray(0), 0, 0)
792  for token in tokens:
793  x._datastore._appendstore(Bits._init_with_token(*token)._datastore)
794  assert x._assertsanity()
795  if len(_cache) < CACHE_SIZE:
796  _cache[auto] = x
797  return x
798  if isinstance(auto, Bits):
799  return auto
800  except TypeError:
801  pass
802  x = super(Bits, cls).__new__(cls)
803  x._initialise(auto, length, offset, **kwargs)
804  return x
805 
806  def _initialise(self, auto, length, offset, **kwargs):
807  if length is not None and length < 0:
808  raise CreationError("bitstring length cannot be negative.")
809  if offset is not None and offset < 0:
810  raise CreationError("offset must be >= 0.")
811  if auto is not None:
812  self._initialise_from_auto(auto, length, offset)
813  return
814  if not kwargs:
815  # No initialisers, so initialise with nothing or zero bits
816  if length is not None and length != 0:
817  data = bytearray((length + 7) // 8)
818  self._setbytes_unsafe(data, length, 0)
819  return
820  self._setbytes_unsafe(bytearray(0), 0, 0)
821  return
822  k, v = kwargs.popitem()
823  try:
824  init_without_length_or_offset[k](self, v)
825  if length is not None or offset is not None:
826  raise CreationError("Cannot use length or offset with this initialiser.")
827  except KeyError:
828  try:
829  init_with_length_only[k](self, v, length)
830  if offset is not None:
831  raise CreationError("Cannot use offset with this initialiser.")
832  except KeyError:
833  if offset is None:
834  offset = 0
835  try:
836  init_with_length_and_offset[k](self, v, length, offset)
837  except KeyError:
838  raise CreationError("Unrecognised keyword '{0}' used to initialise.", k)
839 
840  def _initialise_from_auto(self, auto, length, offset):
841  if offset is None:
842  offset = 0
843  self._setauto(auto, length, offset)
844  return
845 
846  def __copy__(self):
847  """Return a new copy of the Bits for the copy module."""
848  # Note that if you want a new copy (different ID), use _copy instead.
849  # The copy can return self as it's immutable.
850  return self
851 
852  def __lt__(self, other):
853  raise TypeError("unorderable type: {0}".format(type(self).__name__))
854 
855  def __gt__(self, other):
856  raise TypeError("unorderable type: {0}".format(type(self).__name__))
857 
858  def __le__(self, other):
859  raise TypeError("unorderable type: {0}".format(type(self).__name__))
860 
861  def __ge__(self, other):
862  raise TypeError("unorderable type: {0}".format(type(self).__name__))
863 
864  def __add__(self, bs):
865  """Concatenate bitstrings and return new bitstring.
866 
867  bs -- the bitstring to append.
868 
869  """
870  bs = Bits(bs)
871  if bs.len <= self.len:
872  s = self._copy()
873  s._append(bs)
874  else:
875  s = bs._copy()
876  s = self.__class__(s)
877  s._prepend(self)
878  return s
879 
880  def __radd__(self, bs):
881  """Append current bitstring to bs and return new bitstring.
882 
883  bs -- the string for the 'auto' initialiser that will be appended to.
884 
885  """
886  bs = self._converttobitstring(bs)
887  return bs.__add__(self)
888 
889  def __getitem__(self, key):
890  """Return a new bitstring representing a slice of the current bitstring.
891 
892  Indices are in units of the step parameter (default 1 bit).
893  Stepping is used to specify the number of bits in each item.
894 
895  >>> print BitArray('0b00110')[1:4]
896  '0b011'
897  >>> print BitArray('0x00112233')[1:3:8]
898  '0x1122'
899 
900  """
901  length = self.len
902  try:
903  step = key.step if key.step is not None else 1
904  except AttributeError:
905  # single element
906  if key < 0:
907  key += length
908  if not 0 <= key < length:
909  raise IndexError("Slice index out of range.")
910  # Single bit, return True or False
911  return self._datastore.getbit(key)
912  else:
913  if step != 1:
914  # convert to binary string and use string slicing
915  bs = self.__class__()
916  bs._setbin_unsafe(self._getbin().__getitem__(key))
917  return bs
918  start, stop = 0, length
919  if key.start is not None:
920  start = key.start
921  if key.start < 0:
922  start += stop
923  if key.stop is not None:
924  stop = key.stop
925  if key.stop < 0:
926  stop += length
927  start = max(start, 0)
928  stop = min(stop, length)
929  if start < stop:
930  return self._slice(start, stop)
931  else:
932  return self.__class__()
933 
934  def __len__(self):
935  """Return the length of the bitstring in bits."""
936  return self._getlength()
937 
938  def __str__(self):
939  """Return approximate string representation of bitstring for printing.
940 
941  Short strings will be given wholly in hexadecimal or binary. Longer
942  strings may be part hexadecimal and part binary. Very long strings will
943  be truncated with '...'.
944 
945  """
946  length = self.len
947  if not length:
948  return ''
949  if length > MAX_CHARS * 4:
950  # Too long for hex. Truncate...
951  return ''.join(('0x', self._readhex(MAX_CHARS * 4, 0), '...'))
952  # If it's quite short and we can't do hex then use bin
953  if length < 32 and length % 4 != 0:
954  return '0b' + self.bin
955  # If we can use hex then do so
956  if not length % 4:
957  return '0x' + self.hex
958  # Otherwise first we do as much as we can in hex
959  # then add on 1, 2 or 3 bits on at the end
960  bits_at_end = length % 4
961  return ''.join(('0x', self._readhex(length - bits_at_end, 0),
962  ', ', '0b',
963  self._readbin(bits_at_end, length - bits_at_end)))
964 
965  def __repr__(self):
966  """Return representation that could be used to recreate the bitstring.
967 
968  If the returned string is too long it will be truncated. See __str__().
969 
970  """
971  length = self.len
972  if isinstance(self._datastore._rawarray, MmapByteArray):
973  offsetstring = ''
974  if self._datastore.byteoffset or self._offset:
975  offsetstring = ", offset=%d" % (self._datastore._rawarray.byteoffset * 8 + self._offset)
976  lengthstring = ", length=%d" % length
977  return "{0}(filename='{1}'{2}{3})".format(self.__class__.__name__,
978  self._datastore._rawarray.source.name, lengthstring, offsetstring)
979  else:
980  s = self.__str__()
981  lengthstring = ''
982  if s.endswith('...'):
983  lengthstring = " # length={0}".format(length)
984  return "{0}('{1}'){2}".format(self.__class__.__name__, s, lengthstring)
985 
986  def __eq__(self, bs):
987  """Return True if two bitstrings have the same binary representation.
988 
989  >>> BitArray('0b1110') == '0xe'
990  True
991 
992  """
993  try:
994  bs = Bits(bs)
995  except TypeError:
996  return False
997  return equal(self._datastore, bs._datastore)
998 
999  def __ne__(self, bs):
1000  """Return False if two bitstrings have the same binary representation.
1001 
1002  >>> BitArray('0b111') == '0x7'
1003  False
1004 
1005  """
1006  return not self.__eq__(bs)
1007 
1008  def __invert__(self):
1009  """Return bitstring with every bit inverted.
1010 
1011  Raises Error if the bitstring is empty.
1012 
1013  """
1014  if not self.len:
1015  raise Error("Cannot invert empty bitstring.")
1016  s = self._copy()
1017  s._invert_all()
1018  return s
1019 
1020  def __lshift__(self, n):
1021  """Return bitstring with bits shifted by n to the left.
1022 
1023  n -- the number of bits to shift. Must be >= 0.
1024 
1025  """
1026  if n < 0:
1027  raise ValueError("Cannot shift by a negative amount.")
1028  if not self.len:
1029  raise ValueError("Cannot shift an empty bitstring.")
1030  n = min(n, self.len)
1031  s = self._slice(n, self.len)
1032  s._append(Bits(n))
1033  return s
1034 
1035  def __rshift__(self, n):
1036  """Return bitstring with bits shifted by n to the right.
1037 
1038  n -- the number of bits to shift. Must be >= 0.
1039 
1040  """
1041  if n < 0:
1042  raise ValueError("Cannot shift by a negative amount.")
1043  if not self.len:
1044  raise ValueError("Cannot shift an empty bitstring.")
1045  if not n:
1046  return self._copy()
1047  s = self.__class__(length=min(n, self.len))
1048  s._append(self[:-n])
1049  return s
1050 
1051  def __mul__(self, n):
1052  """Return bitstring consisting of n concatenations of self.
1053 
1054  Called for expression of the form 'a = b*3'.
1055  n -- The number of concatenations. Must be >= 0.
1056 
1057  """
1058  if n < 0:
1059  raise ValueError("Cannot multiply by a negative integer.")
1060  if not n:
1061  return self.__class__()
1062  s = self._copy()
1063  s._imul(n)
1064  return s
1065 
1066  def __rmul__(self, n):
1067  """Return bitstring consisting of n concatenations of self.
1068 
1069  Called for expressions of the form 'a = 3*b'.
1070  n -- The number of concatenations. Must be >= 0.
1071 
1072  """
1073  return self.__mul__(n)
1074 
1075  def __and__(self, bs):
1076  """Bit-wise 'and' between two bitstrings. Returns new bitstring.
1077 
1078  bs -- The bitstring to '&' with.
1079 
1080  Raises ValueError if the two bitstrings have differing lengths.
1081 
1082  """
1083  bs = Bits(bs)
1084  if self.len != bs.len:
1085  raise ValueError("Bitstrings must have the same length "
1086  "for & operator.")
1087  s = self._copy()
1088  s._iand(bs)
1089  return s
1090 
1091  def __rand__(self, bs):
1092  """Bit-wise 'and' between two bitstrings. Returns new bitstring.
1093 
1094  bs -- the bitstring to '&' with.
1095 
1096  Raises ValueError if the two bitstrings have differing lengths.
1097 
1098  """
1099  return self.__and__(bs)
1100 
1101  def __or__(self, bs):
1102  """Bit-wise 'or' between two bitstrings. Returns new bitstring.
1103 
1104  bs -- The bitstring to '|' with.
1105 
1106  Raises ValueError if the two bitstrings have differing lengths.
1107 
1108  """
1109  bs = Bits(bs)
1110  if self.len != bs.len:
1111  raise ValueError("Bitstrings must have the same length "
1112  "for | operator.")
1113  s = self._copy()
1114  s._ior(bs)
1115  return s
1116 
1117  def __ror__(self, bs):
1118  """Bit-wise 'or' between two bitstrings. Returns new bitstring.
1119 
1120  bs -- The bitstring to '|' with.
1121 
1122  Raises ValueError if the two bitstrings have differing lengths.
1123 
1124  """
1125  return self.__or__(bs)
1126 
1127  def __xor__(self, bs):
1128  """Bit-wise 'xor' between two bitstrings. Returns new bitstring.
1129 
1130  bs -- The bitstring to '^' with.
1131 
1132  Raises ValueError if the two bitstrings have differing lengths.
1133 
1134  """
1135  bs = Bits(bs)
1136  if self.len != bs.len:
1137  raise ValueError("Bitstrings must have the same length "
1138  "for ^ operator.")
1139  s = self._copy()
1140  s._ixor(bs)
1141  return s
1142 
1143  def __rxor__(self, bs):
1144  """Bit-wise 'xor' between two bitstrings. Returns new bitstring.
1145 
1146  bs -- The bitstring to '^' with.
1147 
1148  Raises ValueError if the two bitstrings have differing lengths.
1149 
1150  """
1151  return self.__xor__(bs)
1152 
1153  def __contains__(self, bs):
1154  """Return whether bs is contained in the current bitstring.
1155 
1156  bs -- The bitstring to search for.
1157 
1158  """
1159  # Don't want to change pos
1160  try:
1161  pos = self._pos
1162  except AttributeError:
1163  pass
1164  found = Bits.find(self, bs, bytealigned=False)
1165  try:
1166  self._pos = pos
1167  except AttributeError:
1168  pass
1169  return bool(found)
1170 
1171  def __hash__(self):
1172  """Return an integer hash of the object."""
1173  # We can't in general hash the whole bitstring (it could take hours!)
1174  # So instead take some bits from the start and end.
1175  if self.len <= 160:
1176  # Use the whole bitstring.
1177  shorter = self
1178  else:
1179  # Take 10 bytes from start and end
1180  shorter = self[:80] + self[-80:]
1181  h = 0
1182  for byte in shorter.tobytes():
1183  try:
1184  h = (h << 4) + ord(byte)
1185  except TypeError:
1186  # Python 3
1187  h = (h << 4) + byte
1188  g = h & 0xf0000000
1189  if g & (1 << 31):
1190  h ^= (g >> 24)
1191  h ^= g
1192  return h % 1442968193
1193 
1194  # This is only used in Python 2.x...
1195  def __nonzero__(self):
1196  """Return True if any bits are set to 1, otherwise return False."""
1197  return self.any(True)
1198 
1199  # ...whereas this is used in Python 3.x
1200  __bool__ = __nonzero__
1201 
1202  def _assertsanity(self):
1203  """Check internal self consistency as a debugging aid."""
1204  assert self.len >= 0
1205  assert 0 <= self._offset, "offset={0}".format(self._offset)
1206  assert (self.len + self._offset + 7) // 8 == self._datastore.bytelength + self._datastore.byteoffset
1207  return True
1208 
1209  @classmethod
1210  def _init_with_token(cls, name, token_length, value):
1211  if token_length is not None:
1212  token_length = int(token_length)
1213  if token_length == 0:
1214  return cls()
1215  # For pad token just return the length in zero bits
1216  if name == 'pad':
1217  return cls(token_length)
1218 
1219  if value is None:
1220  if token_length is None:
1221  error = "Token has no value ({0}=???).".format(name)
1222  else:
1223  error = "Token has no value ({0}:{1}=???).".format(name, token_length)
1224  raise ValueError(error)
1225  try:
1226  b = cls(**{_tokenname_to_initialiser[name]: value})
1227  except KeyError:
1228  if name in ('se', 'ue', 'sie', 'uie'):
1229  b = cls(**{name: int(value)})
1230  elif name in ('uint', 'int', 'uintbe', 'intbe', 'uintle', 'intle', 'uintne', 'intne'):
1231  b = cls(**{name: int(value), 'length': token_length})
1232  elif name in ('float', 'floatbe', 'floatle', 'floatne'):
1233  b = cls(**{name: float(value), 'length': token_length})
1234  elif name == 'bool':
1235  if value in (1, 'True', '1'):
1236  b = cls(bool=True)
1237  elif value in (0, 'False', '0'):
1238  b = cls(bool=False)
1239  else:
1240  raise CreationError("bool token can only be 'True' or 'False'.")
1241  else:
1242  raise CreationError("Can't parse token name {0}.", name)
1243  if token_length is not None and b.len != token_length:
1244  msg = "Token with length {0} packed with value of length {1} ({2}:{3}={4})."
1245  raise CreationError(msg, token_length, b.len, name, token_length, value)
1246  return b
1247 
1248  def _clear(self):
1249  """Reset the bitstring to an empty state."""
1250  self._datastore = ByteStore(bytearray(0))
1251 
1252  def _setauto(self, s, length, offset):
1253  """Set bitstring from a bitstring, file, bool, integer, array, iterable or string."""
1254  # As s can be so many different things it's important to do the checks
1255  # in the correct order, as some types are also other allowed types.
1256  # So basestring must be checked before Iterable
1257  # and bytes/bytearray before Iterable but after basestring!
1258  if isinstance(s, Bits):
1259  if length is None:
1260  length = s.len - offset
1261  self._setbytes_unsafe(s._datastore.rawbytes, length, s._offset + offset)
1262  return
1263  if isinstance(s, file):
1264  if offset is None:
1265  offset = 0
1266  if length is None:
1267  length = os.path.getsize(s.name) * 8 - offset
1268  byteoffset, offset = divmod(offset, 8)
1269  bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset
1270  m = MmapByteArray(s, bytelength, byteoffset)
1271  if length + byteoffset * 8 + offset > m.filelength * 8:
1272  raise CreationError("File is not long enough for specified "
1273  "length and offset.")
1274  self._datastore = ConstByteStore(m, length, offset)
1275  return
1276  if length is not None:
1277  raise CreationError("The length keyword isn't applicable to this initialiser.")
1278  if offset:
1279  raise CreationError("The offset keyword isn't applicable to this initialiser.")
1280  if isinstance(s, basestring):
1281  bs = self._converttobitstring(s)
1282  assert bs._offset == 0
1283  self._setbytes_unsafe(bs._datastore.rawbytes, bs.length, 0)
1284  return
1285  if isinstance(s, (bytes, bytearray)):
1286  self._setbytes_unsafe(bytearray(s), len(s) * 8, 0)
1287  return
1288  if isinstance(s, array.array):
1289  b = s.tostring()
1290  self._setbytes_unsafe(bytearray(b), len(b) * 8, 0)
1291  return
1292  if isinstance(s, numbers.Integral):
1293  # Initialise with s zero bits.
1294  if s < 0:
1295  msg = "Can't create bitstring of negative length {0}."
1296  raise CreationError(msg, s)
1297  data = bytearray((s + 7) // 8)
1298  self._datastore = ByteStore(data, s, 0)
1299  return
1300  if isinstance(s, collections.Iterable):
1301  # Evaluate each item as True or False and set bits to 1 or 0.
1302  self._setbin_unsafe(''.join(str(int(bool(x))) for x in s))
1303  return
1304  raise TypeError("Cannot initialise bitstring from {0}.".format(type(s)))
1305 
1306  def _setfile(self, filename, length, offset):
1307  """Use file as source of bits."""
1308  source = open(filename, 'rb')
1309  if offset is None:
1310  offset = 0
1311  if length is None:
1312  length = os.path.getsize(source.name) * 8 - offset
1313  byteoffset, offset = divmod(offset, 8)
1314  bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset
1315  m = MmapByteArray(source, bytelength, byteoffset)
1316  if length + byteoffset * 8 + offset > m.filelength * 8:
1317  raise CreationError("File is not long enough for specified "
1318  "length and offset.")
1319  self._datastore = ConstByteStore(m, length, offset)
1320 
1321  def _setbytes_safe(self, data, length=None, offset=0):
1322  """Set the data from a string."""
1323  data = bytearray(data)
1324  if length is None:
1325  # Use to the end of the data
1326  length = len(data) * 8 - offset
1327  self._datastore = ByteStore(data, length, offset)
1328  else:
1329  if length + offset > len(data) * 8:
1330  msg = "Not enough data present. Need {0} bits, have {1}."
1331  raise CreationError(msg, length + offset, len(data) * 8)
1332  if length == 0:
1333  self._datastore = ByteStore(bytearray(0))
1334  else:
1335  self._datastore = ByteStore(data, length, offset)
1336 
1337  def _setbytes_unsafe(self, data, length, offset):
1338  """Unchecked version of _setbytes_safe."""
1339  self._datastore = ByteStore(data[:], length, offset)
1340  assert self._assertsanity()
1341 
1342  def _readbytes(self, length, start):
1343  """Read bytes and return them. Note that length is in bits."""
1344  assert length % 8 == 0
1345  assert start + length <= self.len
1346  if not (start + self._offset) % 8:
1347  return bytes(self._datastore.getbyteslice((start + self._offset) // 8,
1348  (start + self._offset + length) // 8))
1349  return self._slice(start, start + length).tobytes()
1350 
1351  def _getbytes(self):
1352  """Return the data as an ordinary string."""
1353  if self.len % 8:
1354  raise InterpretError("Cannot interpret as bytes unambiguously - "
1355  "not multiple of 8 bits.")
1356  return self._readbytes(self.len, 0)
1357 
1358  def _setuint(self, uint, length=None):
1359  """Reset the bitstring to have given unsigned int interpretation."""
1360  try:
1361  if length is None:
1362  # Use the whole length. Deliberately not using .len here.
1363  length = self._datastore.bitlength
1364  except AttributeError:
1365  # bitstring doesn't have a _datastore as it hasn't been created!
1366  pass
1367  # TODO: All this checking code should be hoisted out of here!
1368  if length is None or length == 0:
1369  raise CreationError("A non-zero length must be specified with a "
1370  "uint initialiser.")
1371  if uint >= (1 << length):
1372  msg = "{0} is too large an unsigned integer for a bitstring of length {1}. "\
1373  "The allowed range is [0, {2}]."
1374  raise CreationError(msg, uint, length, (1 << length) - 1)
1375  if uint < 0:
1376  raise CreationError("uint cannot be initialsed by a negative number.")
1377  s = hex(uint)[2:]
1378  s = s.rstrip('L')
1379  if len(s) & 1:
1380  s = '0' + s
1381  try:
1382  data = bytes.fromhex(s)
1383  except AttributeError:
1384  # the Python 2.x way
1385  data = binascii.unhexlify(s)
1386  # Now add bytes as needed to get the right length.
1387  extrabytes = ((length + 7) // 8) - len(data)
1388  if extrabytes > 0:
1389  data = b'\x00' * extrabytes + data
1390  offset = 8 - (length % 8)
1391  if offset == 8:
1392  offset = 0
1393  self._setbytes_unsafe(bytearray(data), length, offset)
1394 
1395  def _readuint(self, length, start):
1396  """Read bits and interpret as an unsigned int."""
1397  if not length:
1398  raise InterpretError("Cannot interpret a zero length bitstring "
1399  "as an integer.")
1400  offset = self._offset
1401  startbyte = (start + offset) // 8
1402  endbyte = (start + offset + length - 1) // 8
1403 
1404  b = binascii.hexlify(bytes(self._datastore.getbyteslice(startbyte, endbyte + 1)))
1405  assert b
1406  i = int(b, 16)
1407  final_bits = 8 - ((start + offset + length) % 8)
1408  if final_bits != 8:
1409  i >>= final_bits
1410  i &= (1 << length) - 1
1411  return i
1412 
1413  def _getuint(self):
1414  """Return data as an unsigned int."""
1415  return self._readuint(self.len, 0)
1416 
1417  def _setint(self, int_, length=None):
1418  """Reset the bitstring to have given signed int interpretation."""
1419  # If no length given, and we've previously been given a length, use it.
1420  if length is None and hasattr(self, 'len') and self.len != 0:
1421  length = self.len
1422  if length is None or length == 0:
1423  raise CreationError("A non-zero length must be specified with an int initialiser.")
1424  if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)):
1425  raise CreationError("{0} is too large a signed integer for a bitstring of length {1}. "
1426  "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)),
1427  (1 << (length - 1)) - 1)
1428  if int_ >= 0:
1429  self._setuint(int_, length)
1430  return
1431  # TODO: We should decide whether to just use the _setuint, or to do the bit flipping,
1432  # based upon which will be quicker. If the -ive number is less than half the maximum
1433  # possible then it's probably quicker to do the bit flipping...
1434 
1435  # Do the 2's complement thing. Add one, set to minus number, then flip bits.
1436  int_ += 1
1437  self._setuint(-int_, length)
1438  self._invert_all()
1439 
1440  def _readint(self, length, start):
1441  """Read bits and interpret as a signed int"""
1442  ui = self._readuint(length, start)
1443  if not ui >> (length - 1):
1444  # Top bit not set, number is positive
1445  return ui
1446  # Top bit is set, so number is negative
1447  tmp = (~(ui - 1)) & ((1 << length) - 1)
1448  return -tmp
1449 
1450  def _getint(self):
1451  """Return data as a two's complement signed int."""
1452  return self._readint(self.len, 0)
1453 
1454  def _setuintbe(self, uintbe, length=None):
1455  """Set the bitstring to a big-endian unsigned int interpretation."""
1456  if length is not None and length % 8 != 0:
1457  raise CreationError("Big-endian integers must be whole-byte. "
1458  "Length = {0} bits.", length)
1459  self._setuint(uintbe, length)
1460 
1461  def _readuintbe(self, length, start):
1462  """Read bits and interpret as a big-endian unsigned int."""
1463  if length % 8:
1464  raise InterpretError("Big-endian integers must be whole-byte. "
1465  "Length = {0} bits.", length)
1466  return self._readuint(length, start)
1467 
1468  def _getuintbe(self):
1469  """Return data as a big-endian two's complement unsigned int."""
1470  return self._readuintbe(self.len, 0)
1471 
1472  def _setintbe(self, intbe, length=None):
1473  """Set bitstring to a big-endian signed int interpretation."""
1474  if length is not None and length % 8 != 0:
1475  raise CreationError("Big-endian integers must be whole-byte. "
1476  "Length = {0} bits.", length)
1477  self._setint(intbe, length)
1478 
1479  def _readintbe(self, length, start):
1480  """Read bits and interpret as a big-endian signed int."""
1481  if length % 8:
1482  raise InterpretError("Big-endian integers must be whole-byte. "
1483  "Length = {0} bits.", length)
1484  return self._readint(length, start)
1485 
1486  def _getintbe(self):
1487  """Return data as a big-endian two's complement signed int."""
1488  return self._readintbe(self.len, 0)
1489 
1490  def _setuintle(self, uintle, length=None):
1491  if length is not None and length % 8 != 0:
1492  raise CreationError("Little-endian integers must be whole-byte. "
1493  "Length = {0} bits.", length)
1494  self._setuint(uintle, length)
1495  self._reversebytes(0, self.len)
1496 
1497  def _readuintle(self, length, start):
1498  """Read bits and interpret as a little-endian unsigned int."""
1499  if length % 8:
1500  raise InterpretError("Little-endian integers must be whole-byte. "
1501  "Length = {0} bits.", length)
1502  assert start + length <= self.len
1503  absolute_pos = start + self._offset
1504  startbyte, offset = divmod(absolute_pos, 8)
1505  val = 0
1506  if not offset:
1507  endbyte = (absolute_pos + length - 1) // 8
1508  chunksize = 4 # for 'L' format
1509  while endbyte - chunksize + 1 >= startbyte:
1510  val <<= 8 * chunksize
1511  val += struct.unpack('<L', bytes(self._datastore.getbyteslice(endbyte + 1 - chunksize, endbyte + 1)))[0]
1512  endbyte -= chunksize
1513  for b in xrange(endbyte, startbyte - 1, -1):
1514  val <<= 8
1515  val += self._datastore.getbyte(b)
1516  else:
1517  data = self._slice(start, start + length)
1518  assert data.len % 8 == 0
1519  data._reversebytes(0, self.len)
1520  for b in bytearray(data.bytes):
1521  val <<= 8
1522  val += b
1523  return val
1524 
1525  def _getuintle(self):
1526  return self._readuintle(self.len, 0)
1527 
1528  def _setintle(self, intle, length=None):
1529  if length is not None and length % 8 != 0:
1530  raise CreationError("Little-endian integers must be whole-byte. "
1531  "Length = {0} bits.", length)
1532  self._setint(intle, length)
1533  self._reversebytes(0, self.len)
1534 
1535  def _readintle(self, length, start):
1536  """Read bits and interpret as a little-endian signed int."""
1537  ui = self._readuintle(length, start)
1538  if not ui >> (length - 1):
1539  # Top bit not set, number is positive
1540  return ui
1541  # Top bit is set, so number is negative
1542  tmp = (~(ui - 1)) & ((1 << length) - 1)
1543  return -tmp
1544 
1545  def _getintle(self):
1546  return self._readintle(self.len, 0)
1547 
1548  def _setfloat(self, f, length=None):
1549  # If no length given, and we've previously been given a length, use it.
1550  if length is None and hasattr(self, 'len') and self.len != 0:
1551  length = self.len
1552  if length is None or length == 0:
1553  raise CreationError("A non-zero length must be specified with a "
1554  "float initialiser.")
1555  if length == 32:
1556  b = struct.pack('>f', f)
1557  elif length == 64:
1558  b = struct.pack('>d', f)
1559  else:
1560  raise CreationError("floats can only be 32 or 64 bits long, "
1561  "not {0} bits", length)
1562  self._setbytes_unsafe(bytearray(b), length, 0)
1563 
1564  def _readfloat(self, length, start):
1565  """Read bits and interpret as a float."""
1566  if not (start + self._offset) % 8:
1567  startbyte = (start + self._offset) // 8
1568  if length == 32:
1569  f, = struct.unpack('>f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4)))
1570  elif length == 64:
1571  f, = struct.unpack('>d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8)))
1572  else:
1573  if length == 32:
1574  f, = struct.unpack('>f', self._readbytes(32, start))
1575  elif length == 64:
1576  f, = struct.unpack('>d', self._readbytes(64, start))
1577  try:
1578  return f
1579  except NameError:
1580  raise InterpretError("floats can only be 32 or 64 bits long, not {0} bits", length)
1581 
1582  def _getfloat(self):
1583  """Interpret the whole bitstring as a float."""
1584  return self._readfloat(self.len, 0)
1585 
1586  def _setfloatle(self, f, length=None):
1587  # If no length given, and we've previously been given a length, use it.
1588  if length is None and hasattr(self, 'len') and self.len != 0:
1589  length = self.len
1590  if length is None or length == 0:
1591  raise CreationError("A non-zero length must be specified with a "
1592  "float initialiser.")
1593  if length == 32:
1594  b = struct.pack('<f', f)
1595  elif length == 64:
1596  b = struct.pack('<d', f)
1597  else:
1598  raise CreationError("floats can only be 32 or 64 bits long, "
1599  "not {0} bits", length)
1600  self._setbytes_unsafe(bytearray(b), length, 0)
1601 
1602  def _readfloatle(self, length, start):
1603  """Read bits and interpret as a little-endian float."""
1604  startbyte, offset = divmod(start + self._offset, 8)
1605  if not offset:
1606  if length == 32:
1607  f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4)))
1608  elif length == 64:
1609  f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8)))
1610  else:
1611  if length == 32:
1612  f, = struct.unpack('<f', self._readbytes(32, start))
1613  elif length == 64:
1614  f, = struct.unpack('<d', self._readbytes(64, start))
1615  try:
1616  return f
1617  except NameError:
1618  raise InterpretError("floats can only be 32 or 64 bits long, "
1619  "not {0} bits", length)
1620 
1621  def _getfloatle(self):
1622  """Interpret the whole bitstring as a little-endian float."""
1623  return self._readfloatle(self.len, 0)
1624 
1625  def _setue(self, i):
1626  """Initialise bitstring with unsigned exponential-Golomb code for integer i.
1627 
1628  Raises CreationError if i < 0.
1629 
1630  """
1631  if i < 0:
1632  raise CreationError("Cannot use negative initialiser for unsigned "
1633  "exponential-Golomb.")
1634  if not i:
1635  self._setbin_unsafe('1')
1636  return
1637  tmp = i + 1
1638  leadingzeros = -1
1639  while tmp > 0:
1640  tmp >>= 1
1641  leadingzeros += 1
1642  remainingpart = i + 1 - (1 << leadingzeros)
1643  binstring = '0' * leadingzeros + '1' + Bits(uint=remainingpart,
1644  length=leadingzeros).bin
1645  self._setbin_unsafe(binstring)
1646 
1647  def _readue(self, pos):
1648  """Return interpretation of next bits as unsigned exponential-Golomb code.
1649 
1650  Raises ReadError if the end of the bitstring is encountered while
1651  reading the code.
1652 
1653  """
1654  oldpos = pos
1655  try:
1656  while not self[pos]:
1657  pos += 1
1658  except IndexError:
1659  raise ReadError("Read off end of bitstring trying to read code.")
1660  leadingzeros = pos - oldpos
1661  codenum = (1 << leadingzeros) - 1
1662  if leadingzeros > 0:
1663  if pos + leadingzeros + 1 > self.len:
1664  raise ReadError("Read off end of bitstring trying to read code.")
1665  codenum += self._readuint(leadingzeros, pos + 1)
1666  pos += leadingzeros + 1
1667  else:
1668  assert codenum == 0
1669  pos += 1
1670  return codenum, pos
1671 
1672  def _getue(self):
1673  """Return data as unsigned exponential-Golomb code.
1674 
1675  Raises InterpretError if bitstring is not a single exponential-Golomb code.
1676 
1677  """
1678  try:
1679  value, newpos = self._readue(0)
1680  if value is None or newpos != self.len:
1681  raise ReadError
1682  except ReadError:
1683  raise InterpretError("Bitstring is not a single exponential-Golomb code.")
1684  return value
1685 
1686  def _setse(self, i):
1687  """Initialise bitstring with signed exponential-Golomb code for integer i."""
1688  if i > 0:
1689  u = (i * 2) - 1
1690  else:
1691  u = -2 * i
1692  self._setue(u)
1693 
1694  def _getse(self):
1695  """Return data as signed exponential-Golomb code.
1696 
1697  Raises InterpretError if bitstring is not a single exponential-Golomb code.
1698 
1699  """
1700  try:
1701  value, newpos = self._readse(0)
1702  if value is None or newpos != self.len:
1703  raise ReadError
1704  except ReadError:
1705  raise InterpretError("Bitstring is not a single exponential-Golomb code.")
1706  return value
1707 
1708  def _readse(self, pos):
1709  """Return interpretation of next bits as a signed exponential-Golomb code.
1710 
1711  Advances position to after the read code.
1712 
1713  Raises ReadError if the end of the bitstring is encountered while
1714  reading the code.
1715 
1716  """
1717  codenum, pos = self._readue(pos)
1718  m = (codenum + 1) // 2
1719  if not codenum % 2:
1720  return -m, pos
1721  else:
1722  return m, pos
1723 
1724  def _setuie(self, i):
1725  """Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i.
1726 
1727  Raises CreationError if i < 0.
1728 
1729  """
1730  if i < 0:
1731  raise CreationError("Cannot use negative initialiser for unsigned "
1732  "interleaved exponential-Golomb.")
1733  self._setbin_unsafe('1' if i == 0 else '0' + '0'.join(bin(i + 1)[3:]) + '1')
1734 
1735  def _readuie(self, pos):
1736  """Return interpretation of next bits as unsigned interleaved exponential-Golomb code.
1737 
1738  Raises ReadError if the end of the bitstring is encountered while
1739  reading the code.
1740 
1741  """
1742  try:
1743  codenum = 1
1744  while not self[pos]:
1745  pos += 1
1746  codenum <<= 1
1747  codenum += self[pos]
1748  pos += 1
1749  pos += 1
1750  except IndexError:
1751  raise ReadError("Read off end of bitstring trying to read code.")
1752  codenum -= 1
1753  return codenum, pos
1754 
1755  def _getuie(self):
1756  """Return data as unsigned interleaved exponential-Golomb code.
1757 
1758  Raises InterpretError if bitstring is not a single exponential-Golomb code.
1759 
1760  """
1761  try:
1762  value, newpos = self._readuie(0)
1763  if value is None or newpos != self.len:
1764  raise ReadError
1765  except ReadError:
1766  raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.")
1767  return value
1768 
1769  def _setsie(self, i):
1770  """Initialise bitstring with signed interleaved exponential-Golomb code for integer i."""
1771  if not i:
1772  self._setbin_unsafe('1')
1773  else:
1774  self._setuie(abs(i))
1775  self._append(Bits([i < 0]))
1776 
1777  def _getsie(self):
1778  """Return data as signed interleaved exponential-Golomb code.
1779 
1780  Raises InterpretError if bitstring is not a single exponential-Golomb code.
1781 
1782  """
1783  try:
1784  value, newpos = self._readsie(0)
1785  if value is None or newpos != self.len:
1786  raise ReadError
1787  except ReadError:
1788  raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.")
1789  return value
1790 
1791  def _readsie(self, pos):
1792  """Return interpretation of next bits as a signed interleaved exponential-Golomb code.
1793 
1794  Advances position to after the read code.
1795 
1796  Raises ReadError if the end of the bitstring is encountered while
1797  reading the code.
1798 
1799  """
1800  codenum, pos = self._readuie(pos)
1801  if not codenum:
1802  return 0, pos
1803  try:
1804  if self[pos]:
1805  return -codenum, pos + 1
1806  else:
1807  return codenum, pos + 1
1808  except IndexError:
1809  raise ReadError("Read off end of bitstring trying to read code.")
1810 
1811  def _setbool(self, value):
1812  # We deliberately don't want to have implicit conversions to bool here.
1813  # If we did then it would be difficult to deal with the 'False' string.
1814  if value in (1, 'True'):
1815  self._setbytes_unsafe(bytearray(b'\x80'), 1, 0)
1816  elif value in (0, 'False'):
1817  self._setbytes_unsafe(bytearray(b'\x00'), 1, 0)
1818  else:
1819  raise CreationError('Cannot initialise boolean with {0}.', value)
1820 
1821  def _getbool(self):
1822  if self.length != 1:
1823  msg = "For a bool interpretation a bitstring must be 1 bit long, not {0} bits."
1824  raise InterpretError(msg, self.length)
1825  return self[0]
1826 
1827  def _readbool(self, pos):
1828  return self[pos], pos + 1
1829 
1830  def _setbin_safe(self, binstring):
1831  """Reset the bitstring to the value given in binstring."""
1832  binstring = tidy_input_string(binstring)
1833  # remove any 0b if present
1834  binstring = binstring.replace('0b', '')
1835  self._setbin_unsafe(binstring)
1836 
1837  def _setbin_unsafe(self, binstring):
1838  """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'."""
1839  length = len(binstring)
1840  # pad with zeros up to byte boundary if needed
1841  boundary = ((length + 7) // 8) * 8
1842  padded_binstring = binstring + '0' * (boundary - length)\
1843  if len(binstring) < boundary else binstring
1844  try:
1845  bytelist = [int(padded_binstring[x:x + 8], 2)
1846  for x in xrange(0, len(padded_binstring), 8)]
1847  except ValueError:
1848  raise CreationError("Invalid character in bin initialiser {0}.", binstring)
1849  self._setbytes_unsafe(bytearray(bytelist), length, 0)
1850 
1851  def _readbin(self, length, start):
1852  """Read bits and interpret as a binary string."""
1853  if not length:
1854  return ''
1855  # Get the byte slice containing our bit slice
1856  startbyte, startoffset = divmod(start + self._offset, 8)
1857  endbyte = (start + self._offset + length - 1) // 8
1858  b = self._datastore.getbyteslice(startbyte, endbyte + 1)
1859  # Convert to a string of '0' and '1's (via a hex string an and int!)
1860  try:
1861  c = "{:0{}b}".format(int(binascii.hexlify(b), 16), 8 * len(b))
1862  except TypeError:
1863  # Hack to get Python 2.6 working
1864  c = "{0:0{1}b}".format(int(binascii.hexlify(str(b)), 16), 8 * len(b))
1865  # Finally chop off any extra bits.
1866  return c[startoffset:startoffset + length]
1867 
1868  def _getbin(self):
1869  """Return interpretation as a binary string."""
1870  return self._readbin(self.len, 0)
1871 
1872  def _setoct(self, octstring):
1873  """Reset the bitstring to have the value given in octstring."""
1874  octstring = tidy_input_string(octstring)
1875  # remove any 0o if present
1876  octstring = octstring.replace('0o', '')
1877  binlist = []
1878  for i in octstring:
1879  try:
1880  if not 0 <= int(i) < 8:
1881  raise ValueError
1882  binlist.append(OCT_TO_BITS[int(i)])
1883  except ValueError:
1884  raise CreationError("Invalid symbol '{0}' in oct initialiser.", i)
1885  self._setbin_unsafe(''.join(binlist))
1886 
1887  def _readoct(self, length, start):
1888  """Read bits and interpret as an octal string."""
1889  if length % 3:
1890  raise InterpretError("Cannot convert to octal unambiguously - "
1891  "not multiple of 3 bits.")
1892  if not length:
1893  return ''
1894  # Get main octal bit by converting from int.
1895  # Strip starting 0 or 0o depending on Python version.
1896  end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:]
1897  if end.endswith('L'):
1898  end = end[:-1]
1899  middle = '0' * (length // 3 - len(end))
1900  return middle + end
1901 
1902  def _getoct(self):
1903  """Return interpretation as an octal string."""
1904  return self._readoct(self.len, 0)
1905 
1906  def _sethex(self, hexstring):
1907  """Reset the bitstring to have the value given in hexstring."""
1908  hexstring = tidy_input_string(hexstring)
1909  # remove any 0x if present
1910  hexstring = hexstring.replace('0x', '')
1911  length = len(hexstring)
1912  if length % 2:
1913  hexstring += '0'
1914  try:
1915  try:
1916  data = bytearray.fromhex(hexstring)
1917  except TypeError:
1918  # Python 2.6 needs a unicode string (a bug). 2.7 and 3.x work fine.
1919  data = bytearray.fromhex(unicode(hexstring))
1920  except ValueError:
1921  raise CreationError("Invalid symbol in hex initialiser.")
1922  self._setbytes_unsafe(data, length * 4, 0)
1923 
1924  def _readhex(self, length, start):
1925  """Read bits and interpret as a hex string."""
1926  if length % 4:
1927  raise InterpretError("Cannot convert to hex unambiguously - "
1928  "not multiple of 4 bits.")
1929  if not length:
1930  return ''
1931  s = self._slice(start, start + length).tobytes()
1932  try:
1933  s = s.hex() # Available in Python 3.5
1934  except AttributeError:
1935  # This monstrosity is the only thing I could get to work for both 2.6 and 3.1.
1936  # TODO: Is utf-8 really what we mean here?
1937  s = str(binascii.hexlify(s).decode('utf-8'))
1938  # If there's one nibble too many then cut it off
1939  return s[:-1] if (length // 4) % 2 else s
1940 
1941  def _gethex(self):
1942  """Return the hexadecimal representation as a string prefixed with '0x'.
1943 
1944  Raises an InterpretError if the bitstring's length is not a multiple of 4.
1945 
1946  """
1947  return self._readhex(self.len, 0)
1948 
1949  def _getoffset(self):
1950  return self._datastore.offset
1951 
1952  def _getlength(self):
1953  """Return the length of the bitstring in bits."""
1954  return self._datastore.bitlength
1955 
1956  def _ensureinmemory(self):
1957  """Ensure the data is held in memory, not in a file."""
1958  self._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength),
1959  self.len, self._offset)
1960 
1961  @classmethod
1962  def _converttobitstring(cls, bs, offset=0, cache={}):
1963  """Convert bs to a bitstring and return it.
1964 
1965  offset gives the suggested bit offset of first significant
1966  bit, to optimise append etc.
1967 
1968  """
1969  if isinstance(bs, Bits):
1970  return bs
1971  try:
1972  return cache[(bs, offset)]
1973  except KeyError:
1974  if isinstance(bs, basestring):
1975  b = cls()
1976  try:
1977  _, tokens = tokenparser(bs)
1978  except ValueError as e:
1979  raise CreationError(*e.args)
1980  if tokens:
1981  b._append(Bits._init_with_token(*tokens[0]))
1982  b._datastore = offsetcopy(b._datastore, offset)
1983  for token in tokens[1:]:
1984  b._append(Bits._init_with_token(*token))
1985  assert b._assertsanity()
1986  assert b.len == 0 or b._offset == offset
1987  if len(cache) < CACHE_SIZE:
1988  cache[(bs, offset)] = b
1989  return b
1990  except TypeError:
1991  # Unhashable type
1992  pass
1993  return cls(bs)
1994 
1995  def _copy(self):
1996  """Create and return a new copy of the Bits (always in memory)."""
1997  s_copy = self.__class__()
1998  s_copy._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength),
1999  self.len, self._offset)
2000  return s_copy
2001 
2002  def _slice(self, start, end):
2003  """Used internally to get a slice, without error checking."""
2004  if end == start:
2005  return self.__class__()
2006  offset = self._offset
2007  startbyte, newoffset = divmod(start + offset, 8)
2008  endbyte = (end + offset - 1) // 8
2009  bs = self.__class__()
2010  bs._setbytes_unsafe(self._datastore.getbyteslice(startbyte, endbyte + 1), end - start, newoffset)
2011  return bs
2012 
2013  def _readtoken(self, name, pos, length):
2014  """Reads a token from the bitstring and returns the result."""
2015  if length is not None and int(length) > self.length - pos:
2016  raise ReadError("Reading off the end of the data. "
2017  "Tried to read {0} bits when only {1} available.".format(int(length), self.length - pos))
2018  try:
2019  val = name_to_read[name](self, length, pos)
2020  return val, pos + length
2021  except KeyError:
2022  if name == 'pad':
2023  return None, pos + length
2024  raise ValueError("Can't parse token {0}:{1}".format(name, length))
2025  except TypeError:
2026  # This is for the 'ue', 'se' and 'bool' tokens. They will also return the new pos.
2027  return name_to_read[name](self, pos)
2028 
2029  def _append(self, bs):
2030  """Append a bitstring to the current bitstring."""
2031  self._datastore._appendstore(bs._datastore)
2032 
2033  def _prepend(self, bs):
2034  """Prepend a bitstring to the current bitstring."""
2035  self._datastore._prependstore(bs._datastore)
2036 
2037  def _reverse(self):
2038  """Reverse all bits in-place."""
2039  # Reverse the contents of each byte
2040  n = [BYTE_REVERSAL_DICT[b] for b in self._datastore.rawbytes]
2041  # Then reverse the order of the bytes
2042  n.reverse()
2043  # The new offset is the number of bits that were unused at the end.
2044  newoffset = 8 - (self._offset + self.len) % 8
2045  if newoffset == 8:
2046  newoffset = 0
2047  self._setbytes_unsafe(bytearray().join(n), self.length, newoffset)
2048 
2049  def _truncatestart(self, bits):
2050  """Truncate bits from the start of the bitstring."""
2051  assert 0 <= bits <= self.len
2052  if not bits:
2053  return
2054  if bits == self.len:
2055  self._clear()
2056  return
2057  bytepos, offset = divmod(self._offset + bits, 8)
2058  self._setbytes_unsafe(self._datastore.getbyteslice(bytepos, self._datastore.bytelength), self.len - bits,
2059  offset)
2060  assert self._assertsanity()
2061 
2062  def _truncateend(self, bits):
2063  """Truncate bits from the end of the bitstring."""
2064  assert 0 <= bits <= self.len
2065  if not bits:
2066  return
2067  if bits == self.len:
2068  self._clear()
2069  return
2070  newlength_in_bytes = (self._offset + self.len - bits + 7) // 8
2071  self._setbytes_unsafe(self._datastore.getbyteslice(0, newlength_in_bytes), self.len - bits,
2072  self._offset)
2073  assert self._assertsanity()
2074 
2075  def _insert(self, bs, pos):
2076  """Insert bs at pos."""
2077  assert 0 <= pos <= self.len
2078  if pos > self.len // 2:
2079  # Inserting nearer end, so cut off end.
2080  end = self._slice(pos, self.len)
2081  self._truncateend(self.len - pos)
2082  self._append(bs)
2083  self._append(end)
2084  else:
2085  # Inserting nearer start, so cut off start.
2086  start = self._slice(0, pos)
2087  self._truncatestart(pos)
2088  self._prepend(bs)
2089  self._prepend(start)
2090  try:
2091  self._pos = pos + bs.len
2092  except AttributeError:
2093  pass
2094  assert self._assertsanity()
2095 
2096  def _overwrite(self, bs, pos):
2097  """Overwrite with bs at pos."""
2098  assert 0 <= pos < self.len
2099  if bs is self:
2100  # Just overwriting with self, so do nothing.
2101  assert pos == 0
2102  return
2103  firstbytepos = (self._offset + pos) // 8
2104  lastbytepos = (self._offset + pos + bs.len - 1) // 8
2105  bytepos, bitoffset = divmod(self._offset + pos, 8)
2106  if firstbytepos == lastbytepos:
2107  mask = ((1 << bs.len) - 1) << (8 - bs.len - bitoffset)
2108  self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask))
2109  d = offsetcopy(bs._datastore, bitoffset)
2110  self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask))
2111  else:
2112  # Do first byte
2113  mask = (1 << (8 - bitoffset)) - 1
2114  self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask))
2115  d = offsetcopy(bs._datastore, bitoffset)
2116  self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask))
2117  # Now do all the full bytes
2118  self._datastore.setbyteslice(firstbytepos + 1, lastbytepos, d.getbyteslice(1, lastbytepos - firstbytepos))
2119  # and finally the last byte
2120  bitsleft = (self._offset + pos + bs.len) % 8
2121  if not bitsleft:
2122  bitsleft = 8
2123  mask = (1 << (8 - bitsleft)) - 1
2124  self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) & mask)
2125  self._datastore.setbyte(lastbytepos,
2126  self._datastore.getbyte(lastbytepos) | (d.getbyte(d.bytelength - 1) & ~mask))
2127  assert self._assertsanity()
2128 
2129  def _delete(self, bits, pos):
2130  """Delete bits at pos."""
2131  assert 0 <= pos <= self.len
2132  assert pos + bits <= self.len
2133  if not pos:
2134  # Cutting bits off at the start.
2135  self._truncatestart(bits)
2136  return
2137  if pos + bits == self.len:
2138  # Cutting bits off at the end.
2139  self._truncateend(bits)
2140  return
2141  if pos > self.len - pos - bits:
2142  # More bits before cut point than after it, so do bit shifting
2143  # on the final bits.
2144  end = self._slice(pos + bits, self.len)
2145  assert self.len - pos > 0
2146  self._truncateend(self.len - pos)
2147  self._append(end)
2148  return
2149  # More bits after the cut point than before it.
2150  start = self._slice(0, pos)
2151  self._truncatestart(pos + bits)
2152  self._prepend(start)
2153  return
2154 
2155  def _reversebytes(self, start, end):
2156  """Reverse bytes in-place."""
2157  # Make the start occur on a byte boundary
2158  # TODO: We could be cleverer here to avoid changing the offset.
2159  newoffset = 8 - (start % 8)
2160  if newoffset == 8:
2161  newoffset = 0
2162  self._datastore = offsetcopy(self._datastore, newoffset)
2163  # Now just reverse the byte data
2164  toreverse = bytearray(self._datastore.getbyteslice((newoffset + start) // 8, (newoffset + end) // 8))
2165  toreverse.reverse()
2166  self._datastore.setbyteslice((newoffset + start) // 8, (newoffset + end) // 8, toreverse)
2167 
2168  def _set(self, pos):
2169  """Set bit at pos to 1."""
2170  assert 0 <= pos < self.len
2171  self._datastore.setbit(pos)
2172 
2173  def _unset(self, pos):
2174  """Set bit at pos to 0."""
2175  assert 0 <= pos < self.len
2176  self._datastore.unsetbit(pos)
2177 
2178  def _invert(self, pos):
2179  """Flip bit at pos 1<->0."""
2180  assert 0 <= pos < self.len
2181  self._datastore.invertbit(pos)
2182 
2183  def _invert_all(self):
2184  """Invert every bit."""
2185  set = self._datastore.setbyte
2186  get = self._datastore.getbyte
2187  for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength):
2188  set(p, 256 + ~get(p))
2189 
2190  def _ilshift(self, n):
2191  """Shift bits by n to the left in place. Return self."""
2192  assert 0 < n <= self.len
2193  self._append(Bits(n))
2194  self._truncatestart(n)
2195  return self
2196 
2197  def _irshift(self, n):
2198  """Shift bits by n to the right in place. Return self."""
2199  assert 0 < n <= self.len
2200  self._prepend(Bits(n))
2201  self._truncateend(n)
2202  return self
2203 
2204  def _imul(self, n):
2205  """Concatenate n copies of self in place. Return self."""
2206  assert n >= 0
2207  if not n:
2208  self._clear()
2209  return self
2210  m = 1
2211  old_len = self.len
2212  while m * 2 < n:
2213  self._append(self)
2214  m *= 2
2215  self._append(self[0:(n - m) * old_len])
2216  return self
2217 
2218  def _inplace_logical_helper(self, bs, f):
2219  """Helper function containing most of the __ior__, __iand__, __ixor__ code."""
2220  # Give the two bitstrings the same offset (modulo 8)
2221  self_byteoffset, self_bitoffset = divmod(self._offset, 8)
2222  bs_byteoffset, bs_bitoffset = divmod(bs._offset, 8)
2223  if bs_bitoffset != self_bitoffset:
2224  if not self_bitoffset:
2225  bs._datastore = offsetcopy(bs._datastore, 0)
2226  else:
2227  self._datastore = offsetcopy(self._datastore, bs_bitoffset)
2228  a = self._datastore.rawbytes
2229  b = bs._datastore.rawbytes
2230  for i in xrange(len(a)):
2231  a[i] = f(a[i + self_byteoffset], b[i + bs_byteoffset])
2232  return self
2233 
2234  def _ior(self, bs):
2235  return self._inplace_logical_helper(bs, operator.ior)
2236 
2237  def _iand(self, bs):
2238  return self._inplace_logical_helper(bs, operator.iand)
2239 
2240  def _ixor(self, bs):
2241  return self._inplace_logical_helper(bs, operator.xor)
2242 
2243  def _readbits(self, length, start):
2244  """Read some bits from the bitstring and return newly constructed bitstring."""
2245  return self._slice(start, start + length)
2246 
2247  def _validate_slice(self, start, end):
2248  """Validate start and end and return them as positive bit positions."""
2249  if start is None:
2250  start = 0
2251  elif start < 0:
2252  start += self.len
2253  if end is None:
2254  end = self.len
2255  elif end < 0:
2256  end += self.len
2257  if not 0 <= end <= self.len:
2258  raise ValueError("end is not a valid position in the bitstring.")
2259  if not 0 <= start <= self.len:
2260  raise ValueError("start is not a valid position in the bitstring.")
2261  if end < start:
2262  raise ValueError("end must not be less than start.")
2263  return start, end
2264 
2265  def unpack(self, fmt, **kwargs):
2266  """Interpret the whole bitstring using fmt and return list.
2267 
2268  fmt -- A single string or a list of strings with comma separated tokens
2269  describing how to interpret the bits in the bitstring. Items
2270  can also be integers, for reading new bitstring of the given length.
2271  kwargs -- A dictionary or keyword-value pairs - the keywords used in the
2272  format string will be replaced with their given value.
2273 
2274  Raises ValueError if the format is not understood. If not enough bits
2275  are available then all bits to the end of the bitstring will be used.
2276 
2277  See the docstring for 'read' for token examples.
2278 
2279  """
2280  return self._readlist(fmt, 0, **kwargs)[0]
2281 
2282  def _readlist(self, fmt, pos, **kwargs):
2283  tokens = []
2284  stretchy_token = None
2285  if isinstance(fmt, basestring):
2286  fmt = [fmt]
2287  # Not very optimal this, but replace integers with 'bits' tokens
2288  # TODO: optimise
2289  for i, f in enumerate(fmt):
2290  if isinstance(f, numbers.Integral):
2291  fmt[i] = "bits:{0}".format(f)
2292  for f_item in fmt:
2293  stretchy, tkns = tokenparser(f_item, tuple(sorted(kwargs.keys())))
2294  if stretchy:
2295  if stretchy_token:
2296  raise Error("It's not possible to have more than one 'filler' token.")
2297  stretchy_token = stretchy
2298  tokens.extend(tkns)
2299  if not stretchy_token:
2300  lst = []
2301  for name, length, _ in tokens:
2302  if length in kwargs:
2303  length = kwargs[length]
2304  if name == 'bytes':
2305  length *= 8
2306  if name in kwargs and length is None:
2307  # Using default 'uint' - the name is really the length.
2308  value, pos = self._readtoken('uint', pos, kwargs[name])
2309  lst.append(value)
2310  continue
2311  value, pos = self._readtoken(name, pos, length)
2312  if value is not None: # Don't append pad tokens
2313  lst.append(value)
2314  return lst, pos
2315  stretchy_token = False
2316  bits_after_stretchy_token = 0
2317  for token in tokens:
2318  name, length, _ = token
2319  if length in kwargs:
2320  length = kwargs[length]
2321  if name == 'bytes':
2322  length *= 8
2323  if name in kwargs and length is None:
2324  # Default 'uint'.
2325  length = kwargs[name]
2326  if stretchy_token:
2327  if name in ('se', 'ue', 'sie', 'uie'):
2328  raise Error("It's not possible to parse a variable"
2329  "length token after a 'filler' token.")
2330  else:
2331  if length is None:
2332  raise Error("It's not possible to have more than "
2333  "one 'filler' token.")
2334  bits_after_stretchy_token += length
2335  if length is None and name not in ('se', 'ue', 'sie', 'uie'):
2336  assert not stretchy_token
2337  stretchy_token = token
2338  bits_left = self.len - pos
2339  return_values = []
2340  for token in tokens:
2341  name, length, _ = token
2342  if token is stretchy_token:
2343  # Set length to the remaining bits
2344  length = max(bits_left - bits_after_stretchy_token, 0)
2345  if length in kwargs:
2346  length = kwargs[length]
2347  if name == 'bytes':
2348  length *= 8
2349  if name in kwargs and length is None:
2350  # Default 'uint'
2351  length = kwargs[name]
2352  if length is not None:
2353  bits_left -= length
2354  value, pos = self._readtoken(name, pos, length)
2355  if value is not None:
2356  return_values.append(value)
2357  return return_values, pos
2358 
2359  def _findbytes(self, bytes_, start, end, bytealigned):
2360  """Quicker version of find when everything's whole byte
2361  and byte aligned.
2362 
2363  """
2364  assert self._datastore.offset == 0
2365  assert bytealigned is True
2366  # Extract data bytes from bitstring to be found.
2367  bytepos = (start + 7) // 8
2368  found = False
2369  p = bytepos
2370  finalpos = end // 8
2371  increment = max(1024, len(bytes_) * 10)
2372  buffersize = increment + len(bytes_)
2373  while p < finalpos:
2374  # Read in file or from memory in overlapping chunks and search the chunks.
2375  buf = bytearray(self._datastore.getbyteslice(p, min(p + buffersize, finalpos)))
2376  pos = buf.find(bytes_)
2377  if pos != -1:
2378  found = True
2379  p += pos
2380  break
2381  p += increment
2382  if not found:
2383  return ()
2384  return (p * 8,)
2385 
2386  def _findregex(self, reg_ex, start, end, bytealigned):
2387  """Find first occurrence of a compiled regular expression.
2388 
2389  Note that this doesn't support arbitrary regexes, in particular they
2390  must match a known length.
2391 
2392  """
2393  p = start
2394  length = len(reg_ex.pattern)
2395  # We grab overlapping chunks of the binary representation and
2396  # do an ordinary string search within that.
2397  increment = max(4096, length * 10)
2398  buffersize = increment + length
2399  while p < end:
2400  buf = self._readbin(min(buffersize, end - p), p)
2401  # Test using regular expressions...
2402  m = reg_ex.search(buf)
2403  if m:
2404  pos = m.start()
2405  # pos = buf.find(targetbin)
2406  # if pos != -1:
2407  # if bytealigned then we only accept byte aligned positions.
2408  if not bytealigned or (p + pos) % 8 == 0:
2409  return (p + pos,)
2410  if bytealigned:
2411  # Advance to just beyond the non-byte-aligned match and try again...
2412  p += pos + 1
2413  continue
2414  p += increment
2415  # Not found, return empty tuple
2416  return ()
2417 
2418  def find(self, bs, start=None, end=None, bytealigned=None):
2419  """Find first occurrence of substring bs.
2420 
2421  Returns a single item tuple with the bit position if found, or an
2422  empty tuple if not found. The bit position (pos property) will
2423  also be set to the start of the substring if it is found.
2424 
2425  bs -- The bitstring to find.
2426  start -- The bit position to start the search. Defaults to 0.
2427  end -- The bit position one past the last bit to search.
2428  Defaults to self.len.
2429  bytealigned -- If True the bitstring will only be
2430  found on byte boundaries.
2431 
2432  Raises ValueError if bs is empty, if start < 0, if end > self.len or
2433  if end < start.
2434 
2435  >>> BitArray('0xc3e').find('0b1111')
2436  (6,)
2437 
2438  """
2439  bs = Bits(bs)
2440  if not bs.len:
2441  raise ValueError("Cannot find an empty bitstring.")
2442  start, end = self._validate_slice(start, end)
2443  if bytealigned is None:
2444  bytealigned = globals()['bytealigned']
2445  if bytealigned and not bs.len % 8 and not self._datastore.offset:
2446  p = self._findbytes(bs.bytes, start, end, bytealigned)
2447  else:
2448  p = self._findregex(re.compile(bs._getbin()), start, end, bytealigned)
2449  # If called from a class that has a pos, set it
2450  try:
2451  self._pos = p[0]
2452  except (AttributeError, IndexError):
2453  pass
2454  return p
2455 
2456  def findall(self, bs, start=None, end=None, count=None, bytealigned=None):
2457  """Find all occurrences of bs. Return generator of bit positions.
2458 
2459  bs -- The bitstring to find.
2460  start -- The bit position to start the search. Defaults to 0.
2461  end -- The bit position one past the last bit to search.
2462  Defaults to self.len.
2463  count -- The maximum number of occurrences to find.
2464  bytealigned -- If True the bitstring will only be found on
2465  byte boundaries.
2466 
2467  Raises ValueError if bs is empty, if start < 0, if end > self.len or
2468  if end < start.
2469 
2470  Note that all occurrences of bs are found, even if they overlap.
2471 
2472  """
2473  if count is not None and count < 0:
2474  raise ValueError("In findall, count must be >= 0.")
2475  bs = Bits(bs)
2476  start, end = self._validate_slice(start, end)
2477  if bytealigned is None:
2478  bytealigned = globals()['bytealigned']
2479  c = 0
2480  if bytealigned and not bs.len % 8 and not self._datastore.offset:
2481  # Use the quick find method
2482  f = self._findbytes
2483  x = bs._getbytes()
2484  else:
2485  f = self._findregex
2486  x = re.compile(bs._getbin())
2487  while True:
2488 
2489  p = f(x, start, end, bytealigned)
2490  if not p:
2491  break
2492  if count is not None and c >= count:
2493  return
2494  c += 1
2495  try:
2496  self._pos = p[0]
2497  except AttributeError:
2498  pass
2499  yield p[0]
2500  if bytealigned:
2501  start = p[0] + 8
2502  else:
2503  start = p[0] + 1
2504  if start >= end:
2505  break
2506  return
2507 
2508  def rfind(self, bs, start=None, end=None, bytealigned=None):
2509  """Find final occurrence of substring bs.
2510 
2511  Returns a single item tuple with the bit position if found, or an
2512  empty tuple if not found. The bit position (pos property) will
2513  also be set to the start of the substring if it is found.
2514 
2515  bs -- The bitstring to find.
2516  start -- The bit position to end the reverse search. Defaults to 0.
2517  end -- The bit position one past the first bit to reverse search.
2518  Defaults to self.len.
2519  bytealigned -- If True the bitstring will only be found on byte
2520  boundaries.
2521 
2522  Raises ValueError if bs is empty, if start < 0, if end > self.len or
2523  if end < start.
2524 
2525  """
2526  bs = Bits(bs)
2527  start, end = self._validate_slice(start, end)
2528  if bytealigned is None:
2529  bytealigned = globals()['bytealigned']
2530  if not bs.len:
2531  raise ValueError("Cannot find an empty bitstring.")
2532  # Search chunks starting near the end and then moving back
2533  # until we find bs.
2534  increment = max(8192, bs.len * 80)
2535  buffersize = min(increment + bs.len, end - start)
2536  pos = max(start, end - buffersize)
2537  while True:
2538  found = list(self.findall(bs, start=pos, end=pos + buffersize,
2539  bytealigned=bytealigned))
2540  if not found:
2541  if pos == start:
2542  return ()
2543  pos = max(start, pos - increment)
2544  continue
2545  return (found[-1],)
2546 
2547  def cut(self, bits, start=None, end=None, count=None):
2548  """Return bitstring generator by cutting into bits sized chunks.
2549 
2550  bits -- The size in bits of the bitstring chunks to generate.
2551  start -- The bit position to start the first cut. Defaults to 0.
2552  end -- The bit position one past the last bit to use in the cut.
2553  Defaults to self.len.
2554  count -- If specified then at most count items are generated.
2555  Default is to cut as many times as possible.
2556 
2557  """
2558  start, end = self._validate_slice(start, end)
2559  if count is not None and count < 0:
2560  raise ValueError("Cannot cut - count must be >= 0.")
2561  if bits <= 0:
2562  raise ValueError("Cannot cut - bits must be >= 0.")
2563  c = 0
2564  while count is None or c < count:
2565  c += 1
2566  nextchunk = self._slice(start, min(start + bits, end))
2567  if nextchunk.len != bits:
2568  return
2569  assert nextchunk._assertsanity()
2570  yield nextchunk
2571  start += bits
2572  return
2573 
2574  def split(self, delimiter, start=None, end=None, count=None,
2575  bytealigned=None):
2576  """Return bitstring generator by splittling using a delimiter.
2577 
2578  The first item returned is the initial bitstring before the delimiter,
2579  which may be an empty bitstring.
2580 
2581  delimiter -- The bitstring used as the divider.
2582  start -- The bit position to start the split. Defaults to 0.
2583  end -- The bit position one past the last bit to use in the split.
2584  Defaults to self.len.
2585  count -- If specified then at most count items are generated.
2586  Default is to split as many times as possible.
2587  bytealigned -- If True splits will only occur on byte boundaries.
2588 
2589  Raises ValueError if the delimiter is empty.
2590 
2591  """
2592  delimiter = Bits(delimiter)
2593  if not delimiter.len:
2594  raise ValueError("split delimiter cannot be empty.")
2595  start, end = self._validate_slice(start, end)
2596  if bytealigned is None:
2597  bytealigned = globals()['bytealigned']
2598  if count is not None and count < 0:
2599  raise ValueError("Cannot split - count must be >= 0.")
2600  if count == 0:
2601  return
2602  if bytealigned and not delimiter.len % 8 and not self._datastore.offset:
2603  # Use the quick find method
2604  f = self._findbytes
2605  x = delimiter._getbytes()
2606  else:
2607  f = self._findregex
2608  x = re.compile(delimiter._getbin())
2609  found = f(x, start, end, bytealigned)
2610  if not found:
2611  # Initial bits are the whole bitstring being searched
2612  yield self._slice(start, end)
2613  return
2614  # yield the bytes before the first occurrence of the delimiter, even if empty
2615  yield self._slice(start, found[0])
2616  startpos = pos = found[0]
2617  c = 1
2618  while count is None or c < count:
2619  pos += delimiter.len
2620  found = f(x, pos, end, bytealigned)
2621  if not found:
2622  # No more occurrences, so return the rest of the bitstring
2623  yield self._slice(startpos, end)
2624  return
2625  c += 1
2626  yield self._slice(startpos, found[0])
2627  startpos = pos = found[0]
2628  # Have generated count bitstrings, so time to quit.
2629  return
2630 
2631  def join(self, sequence):
2632  """Return concatenation of bitstrings joined by self.
2633 
2634  sequence -- A sequence of bitstrings.
2635 
2636  """
2637  s = self.__class__()
2638  i = iter(sequence)
2639  try:
2640  s._append(Bits(next(i)))
2641  while True:
2642  n = next(i)
2643  s._append(self)
2644  s._append(Bits(n))
2645  except StopIteration:
2646  pass
2647  return s
2648 
2649  def tobytes(self):
2650  """Return the bitstring as bytes, padding with zero bits if needed.
2651 
2652  Up to seven zero bits will be added at the end to byte align.
2653 
2654  """
2655  d = offsetcopy(self._datastore, 0).rawbytes
2656  # Need to ensure that unused bits at end are set to zero
2657  unusedbits = 8 - self.len % 8
2658  if unusedbits != 8:
2659  d[-1] &= (0xff << unusedbits)
2660  return bytes(d)
2661 
2662  def tofile(self, f):
2663  """Write the bitstring to a file object, padding with zero bits if needed.
2664 
2665  Up to seven zero bits will be added at the end to byte align.
2666 
2667  """
2668  # If the bitstring is file based then we don't want to read it all
2669  # in to memory.
2670  chunksize = 1024 * 1024 # 1 MB chunks
2671  if not self._offset:
2672  a = 0
2673  bytelen = self._datastore.bytelength
2674  p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
2675  while len(p) == chunksize:
2676  f.write(p)
2677  a += chunksize
2678  p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
2679  f.write(p)
2680  # Now the final byte, ensuring that unused bits at end are set to 0.
2681  bits_in_final_byte = self.len % 8
2682  if not bits_in_final_byte:
2683  bits_in_final_byte = 8
2684  f.write(self[-bits_in_final_byte:].tobytes())
2685  else:
2686  # Really quite inefficient...
2687  a = 0
2688  b = a + chunksize * 8
2689  while b <= self.len:
2690  f.write(self._slice(a, b)._getbytes())
2691  a += chunksize * 8
2692  b += chunksize * 8
2693  if a != self.len:
2694  f.write(self._slice(a, self.len).tobytes())
2695 
2696  def startswith(self, prefix, start=None, end=None):
2697  """Return whether the current bitstring starts with prefix.
2698 
2699  prefix -- The bitstring to search for.
2700  start -- The bit position to start from. Defaults to 0.
2701  end -- The bit position to end at. Defaults to self.len.
2702 
2703  """
2704  prefix = Bits(prefix)
2705  start, end = self._validate_slice(start, end)
2706  if end < start + prefix.len:
2707  return False
2708  end = start + prefix.len
2709  return self._slice(start, end) == prefix
2710 
2711  def endswith(self, suffix, start=None, end=None):
2712  """Return whether the current bitstring ends with suffix.
2713 
2714  suffix -- The bitstring to search for.
2715  start -- The bit position to start from. Defaults to 0.
2716  end -- The bit position to end at. Defaults to self.len.
2717 
2718  """
2719  suffix = Bits(suffix)
2720  start, end = self._validate_slice(start, end)
2721  if start + suffix.len > end:
2722  return False
2723  start = end - suffix.len
2724  return self._slice(start, end) == suffix
2725 
2726  def all(self, value, pos=None):
2727  """Return True if one or many bits are all set to value.
2728 
2729  value -- If value is True then checks for bits set to 1, otherwise
2730  checks for bits set to 0.
2731  pos -- An iterable of bit positions. Negative numbers are treated in
2732  the same way as slice indices. Defaults to the whole bitstring.
2733 
2734  """
2735  value = bool(value)
2736  length = self.len
2737  if pos is None:
2738  pos = xrange(self.len)
2739  for p in pos:
2740  if p < 0:
2741  p += length
2742  if not 0 <= p < length:
2743  raise IndexError("Bit position {0} out of range.".format(p))
2744  if not self._datastore.getbit(p) is value:
2745  return False
2746  return True
2747 
2748  def any(self, value, pos=None):
2749  """Return True if any of one or many bits are set to value.
2750 
2751  value -- If value is True then checks for bits set to 1, otherwise
2752  checks for bits set to 0.
2753  pos -- An iterable of bit positions. Negative numbers are treated in
2754  the same way as slice indices. Defaults to the whole bitstring.
2755 
2756  """
2757  value = bool(value)
2758  length = self.len
2759  if pos is None:
2760  pos = xrange(self.len)
2761  for p in pos:
2762  if p < 0:
2763  p += length
2764  if not 0 <= p < length:
2765  raise IndexError("Bit position {0} out of range.".format(p))
2766  if self._datastore.getbit(p) is value:
2767  return True
2768  return False
2769 
2770  def count(self, value):
2771  """Return count of total number of either zero or one bits.
2772 
2773  value -- If True then bits set to 1 are counted, otherwise bits set
2774  to 0 are counted.
2775 
2776  >>> Bits('0xef').count(1)
2777  7
2778 
2779  """
2780  if not self.len:
2781  return 0
2782  # count the number of 1s (from which it's easy to work out the 0s).
2783  # Don't count the final byte yet.
2784  count = sum(BIT_COUNT[self._datastore.getbyte(i)] for i in xrange(self._datastore.bytelength - 1))
2785  # adjust for bits at start that aren't part of the bitstring
2786  if self._offset:
2787  count -= BIT_COUNT[self._datastore.getbyte(0) >> (8 - self._offset)]
2788  # and count the last 1 - 8 bits at the end.
2789  endbits = self._datastore.bytelength * 8 - (self._offset + self.len)
2790  count += BIT_COUNT[self._datastore.getbyte(self._datastore.bytelength - 1) >> endbits]
2791  return count if value else self.len - count
2792 
2793  # Create native-endian functions as aliases depending on the byteorder
2794  if byteorder == 'little':
2795  _setfloatne = _setfloatle
2796  _readfloatne = _readfloatle
2797  _getfloatne = _getfloatle
2798  _setuintne = _setuintle
2799  _readuintne = _readuintle
2800  _getuintne = _getuintle
2801  _setintne = _setintle
2802  _readintne = _readintle
2803  _getintne = _getintle
2804  else:
2805  _setfloatne = _setfloat
2806  _readfloatne = _readfloat
2807  _getfloatne = _getfloat
2808  _setuintne = _setuintbe
2809  _readuintne = _readuintbe
2810  _getuintne = _getuintbe
2811  _setintne = _setintbe
2812  _readintne = _readintbe
2813  _getintne = _getintbe
2814 
2815  _offset = property(_getoffset)
2816 
2817  len = property(_getlength,
2818  doc="""The length of the bitstring in bits. Read only.
2819  """)
2820  length = property(_getlength,
2821  doc="""The length of the bitstring in bits. Read only.
2822  """)
2823  bool = property(_getbool,
2824  doc="""The bitstring as a bool (True or False). Read only.
2825  """)
2826  hex = property(_gethex,
2827  doc="""The bitstring as a hexadecimal string. Read only.
2828  """)
2829  bin = property(_getbin,
2830  doc="""The bitstring as a binary string. Read only.
2831  """)
2832  oct = property(_getoct,
2833  doc="""The bitstring as an octal string. Read only.
2834  """)
2835  bytes = property(_getbytes,
2836  doc="""The bitstring as a bytes object. Read only.
2837  """)
2838  int = property(_getint,
2839  doc="""The bitstring as a two's complement signed int. Read only.
2840  """)
2841  uint = property(_getuint,
2842  doc="""The bitstring as a two's complement unsigned int. Read only.
2843  """)
2844  float = property(_getfloat,
2845  doc="""The bitstring as a floating point number. Read only.
2846  """)
2847  intbe = property(_getintbe,
2848  doc="""The bitstring as a two's complement big-endian signed int. Read only.
2849  """)
2850  uintbe = property(_getuintbe,
2851  doc="""The bitstring as a two's complement big-endian unsigned int. Read only.
2852  """)
2853  floatbe = property(_getfloat,
2854  doc="""The bitstring as a big-endian floating point number. Read only.
2855  """)
2856  intle = property(_getintle,
2857  doc="""The bitstring as a two's complement little-endian signed int. Read only.
2858  """)
2859  uintle = property(_getuintle,
2860  doc="""The bitstring as a two's complement little-endian unsigned int. Read only.
2861  """)
2862  floatle = property(_getfloatle,
2863  doc="""The bitstring as a little-endian floating point number. Read only.
2864  """)
2865  intne = property(_getintne,
2866  doc="""The bitstring as a two's complement native-endian signed int. Read only.
2867  """)
2868  uintne = property(_getuintne,
2869  doc="""The bitstring as a two's complement native-endian unsigned int. Read only.
2870  """)
2871  floatne = property(_getfloatne,
2872  doc="""The bitstring as a native-endian floating point number. Read only.
2873  """)
2874  ue = property(_getue,
2875  doc="""The bitstring as an unsigned exponential-Golomb code. Read only.
2876  """)
2877  se = property(_getse,
2878  doc="""The bitstring as a signed exponential-Golomb code. Read only.
2879  """)
2880  uie = property(_getuie,
2881  doc="""The bitstring as an unsigned interleaved exponential-Golomb code. Read only.
2882  """)
2883  sie = property(_getsie,
2884  doc="""The bitstring as a signed interleaved exponential-Golomb code. Read only.
2885  """)
2886 
2887 
2888 # Dictionary that maps token names to the function that reads them.
2889 name_to_read = {'uint': Bits._readuint,
2890  'uintle': Bits._readuintle,
2891  'uintbe': Bits._readuintbe,
2892  'uintne': Bits._readuintne,
2893  'int': Bits._readint,
2894  'intle': Bits._readintle,
2895  'intbe': Bits._readintbe,
2896  'intne': Bits._readintne,
2897  'float': Bits._readfloat,
2898  'floatbe': Bits._readfloat, # floatbe is a synonym for float
2899  'floatle': Bits._readfloatle,
2900  'floatne': Bits._readfloatne,
2901  'hex': Bits._readhex,
2902  'oct': Bits._readoct,
2903  'bin': Bits._readbin,
2904  'bits': Bits._readbits,
2905  'bytes': Bits._readbytes,
2906  'ue': Bits._readue,
2907  'se': Bits._readse,
2908  'uie': Bits._readuie,
2909  'sie': Bits._readsie,
2910  'bool': Bits._readbool,
2911  }
2912 
2913 # Dictionaries for mapping init keywords with init functions.
2914 init_with_length_and_offset = {'bytes': Bits._setbytes_safe,
2915  'filename': Bits._setfile,
2916  }
2917 
2918 init_with_length_only = {'uint': Bits._setuint,
2919  'int': Bits._setint,
2920  'float': Bits._setfloat,
2921  'uintbe': Bits._setuintbe,
2922  'intbe': Bits._setintbe,
2923  'floatbe': Bits._setfloat,
2924  'uintle': Bits._setuintle,
2925  'intle': Bits._setintle,
2926  'floatle': Bits._setfloatle,
2927  'uintne': Bits._setuintne,
2928  'intne': Bits._setintne,
2929  'floatne': Bits._setfloatne,
2930  }
2931 
2932 init_without_length_or_offset = {'bin': Bits._setbin_safe,
2933  'hex': Bits._sethex,
2934  'oct': Bits._setoct,
2935  'ue': Bits._setue,
2936  'se': Bits._setse,
2937  'uie': Bits._setuie,
2938  'sie': Bits._setsie,
2939  'bool': Bits._setbool,
2940  }
2941 
2942 
2944  """A container holding a mutable sequence of bits.
2945 
2946  Subclass of the immutable Bits class. Inherits all of its
2947  methods (except __hash__) and adds mutating methods.
2948 
2949  Mutating methods:
2950 
2951  append() -- Append a bitstring.
2952  byteswap() -- Change byte endianness in-place.
2953  insert() -- Insert a bitstring.
2954  invert() -- Flip bit(s) between one and zero.
2955  overwrite() -- Overwrite a section with a new bitstring.
2956  prepend() -- Prepend a bitstring.
2957  replace() -- Replace occurrences of one bitstring with another.
2958  reverse() -- Reverse bits in-place.
2959  rol() -- Rotate bits to the left.
2960  ror() -- Rotate bits to the right.
2961  set() -- Set bit(s) to 1 or 0.
2962 
2963  Methods inherited from Bits:
2964 
2965  all() -- Check if all specified bits are set to 1 or 0.
2966  any() -- Check if any of specified bits are set to 1 or 0.
2967  count() -- Count the number of bits set to 1 or 0.
2968  cut() -- Create generator of constant sized chunks.
2969  endswith() -- Return whether the bitstring ends with a sub-string.
2970  find() -- Find a sub-bitstring in the current bitstring.
2971  findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
2972  join() -- Join bitstrings together using current bitstring.
2973  rfind() -- Seek backwards to find a sub-bitstring.
2974  split() -- Create generator of chunks split by a delimiter.
2975  startswith() -- Return whether the bitstring starts with a sub-bitstring.
2976  tobytes() -- Return bitstring as bytes, padding if needed.
2977  tofile() -- Write bitstring to file, padding if needed.
2978  unpack() -- Interpret bits using format string.
2979 
2980  Special methods:
2981 
2982  Mutating operators are available: [], <<=, >>=, +=, *=, &=, |= and ^=
2983  in addition to the inherited [], ==, !=, +, *, ~, <<, >>, &, | and ^.
2984 
2985  Properties:
2986 
2987  bin -- The bitstring as a binary string.
2988  bool -- For single bit bitstrings, interpret as True or False.
2989  bytepos -- The current byte position in the bitstring.
2990  bytes -- The bitstring as a bytes object.
2991  float -- Interpret as a floating point number.
2992  floatbe -- Interpret as a big-endian floating point number.
2993  floatle -- Interpret as a little-endian floating point number.
2994  floatne -- Interpret as a native-endian floating point number.
2995  hex -- The bitstring as a hexadecimal string.
2996  int -- Interpret as a two's complement signed integer.
2997  intbe -- Interpret as a big-endian signed integer.
2998  intle -- Interpret as a little-endian signed integer.
2999  intne -- Interpret as a native-endian signed integer.
3000  len -- Length of the bitstring in bits.
3001  oct -- The bitstring as an octal string.
3002  pos -- The current bit position in the bitstring.
3003  se -- Interpret as a signed exponential-Golomb code.
3004  ue -- Interpret as an unsigned exponential-Golomb code.
3005  sie -- Interpret as a signed interleaved exponential-Golomb code.
3006  uie -- Interpret as an unsigned interleaved exponential-Golomb code.
3007  uint -- Interpret as a two's complement unsigned integer.
3008  uintbe -- Interpret as a big-endian unsigned integer.
3009  uintle -- Interpret as a little-endian unsigned integer.
3010  uintne -- Interpret as a native-endian unsigned integer.
3011 
3012  """
3013 
3014  __slots__ = ()
3015 
3016  # As BitArray objects are mutable, we shouldn't allow them to be hashed.
3017  __hash__ = None
3018 
3019  def __init__(self, auto=None, length=None, offset=None, **kwargs):
3020  """Either specify an 'auto' initialiser:
3021  auto -- a string of comma separated tokens, an integer, a file object,
3022  a bytearray, a boolean iterable or another bitstring.
3023 
3024  Or initialise via **kwargs with one (and only one) of:
3025  bytes -- raw data as a string, for example read from a binary file.
3026  bin -- binary string representation, e.g. '0b001010'.
3027  hex -- hexadecimal string representation, e.g. '0x2ef'
3028  oct -- octal string representation, e.g. '0o777'.
3029  uint -- an unsigned integer.
3030  int -- a signed integer.
3031  float -- a floating point number.
3032  uintbe -- an unsigned big-endian whole byte integer.
3033  intbe -- a signed big-endian whole byte integer.
3034  floatbe - a big-endian floating point number.
3035  uintle -- an unsigned little-endian whole byte integer.
3036  intle -- a signed little-endian whole byte integer.
3037  floatle -- a little-endian floating point number.
3038  uintne -- an unsigned native-endian whole byte integer.
3039  intne -- a signed native-endian whole byte integer.
3040  floatne -- a native-endian floating point number.
3041  se -- a signed exponential-Golomb code.
3042  ue -- an unsigned exponential-Golomb code.
3043  sie -- a signed interleaved exponential-Golomb code.
3044  uie -- an unsigned interleaved exponential-Golomb code.
3045  bool -- a boolean (True or False).
3046  filename -- a file which will be opened in binary read-only mode.
3047 
3048  Other keyword arguments:
3049  length -- length of the bitstring in bits, if needed and appropriate.
3050  It must be supplied for all integer and float initialisers.
3051  offset -- bit offset to the data. These offset bits are
3052  ignored and this is intended for use when
3053  initialising using 'bytes' or 'filename'.
3054 
3055  """
3056  # For mutable BitArrays we always read in files to memory:
3057  if not isinstance(self._datastore, ByteStore):
3058  self._ensureinmemory()
3059 
3060  def __new__(cls, auto=None, length=None, offset=None, **kwargs):
3061  x = super(BitArray, cls).__new__(cls)
3062  y = Bits.__new__(BitArray, auto, length, offset, **kwargs)
3063  x._datastore = y._datastore
3064  return x
3065 
3066  def __iadd__(self, bs):
3067  """Append bs to current bitstring. Return self.
3068 
3069  bs -- the bitstring to append.
3070 
3071  """
3072  self.append(bs)
3073  return self
3074 
3075  def __copy__(self):
3076  """Return a new copy of the BitArray."""
3077  s_copy = BitArray()
3078  if not isinstance(self._datastore, ByteStore):
3079  # Let them both point to the same (invariant) array.
3080  # If either gets modified then at that point they'll be read into memory.
3081  s_copy._datastore = self._datastore
3082  else:
3083  s_copy._datastore = copy.copy(self._datastore)
3084  return s_copy
3085 
3086  def __setitem__(self, key, value):
3087  """Set item or range to new value.
3088 
3089  Indices are in units of the step parameter (default 1 bit).
3090  Stepping is used to specify the number of bits in each item.
3091 
3092  If the length of the bitstring is changed then pos will be moved
3093  to after the inserted section, otherwise it will remain unchanged.
3094 
3095  >>> s = BitArray('0xff')
3096  >>> s[0:1:4] = '0xe'
3097  >>> print s
3098  '0xef'
3099  >>> s[4:4] = '0x00'
3100  >>> print s
3101  '0xe00f'
3102 
3103  """
3104  try:
3105  # A slice
3106  start, step = 0, 1
3107  if key.step is not None:
3108  step = key.step
3109  except AttributeError:
3110  # single element
3111  if key < 0:
3112  key += self.len
3113  if not 0 <= key < self.len:
3114  raise IndexError("Slice index out of range.")
3115  if isinstance(value, numbers.Integral):
3116  if not value:
3117  self._unset(key)
3118  return
3119  if value in (1, -1):
3120  self._set(key)
3121  return
3122  raise ValueError("Cannot set a single bit with integer {0}.".format(value))
3123  value = Bits(value)
3124  if value.len == 1:
3125  # TODO: this can't be optimal
3126  if value[0]:
3127  self._set(key)
3128  else:
3129  self._unset(key)
3130  else:
3131  self._delete(1, key)
3132  self._insert(value, key)
3133  return
3134  else:
3135  if step != 1:
3136  # convert to binary string and use string slicing
3137  # TODO: Horribly inefficent
3138  temp = list(self._getbin())
3139  v = list(Bits(value)._getbin())
3140  temp.__setitem__(key, v)
3141  self._setbin_unsafe(''.join(temp))
3142  return
3143 
3144  # If value is an integer then we want to set the slice to that
3145  # value rather than initialise a new bitstring of that length.
3146  if not isinstance(value, numbers.Integral):
3147  try:
3148  # TODO: Better way than calling constructor here?
3149  value = Bits(value)
3150  except TypeError:
3151  raise TypeError("Bitstring, integer or string expected. "
3152  "Got {0}.".format(type(value)))
3153  if key.start is not None:
3154  start = key.start
3155  if key.start < 0:
3156  start += self.len
3157  if start < 0:
3158  start = 0
3159  stop = self.len
3160  if key.stop is not None:
3161  stop = key.stop
3162  if key.stop < 0:
3163  stop += self.len
3164  if start > stop:
3165  # The standard behaviour for lists is to just insert at the
3166  # start position if stop < start and step == 1.
3167  stop = start
3168  if isinstance(value, numbers.Integral):
3169  if value >= 0:
3170  value = self.__class__(uint=value, length=stop - start)
3171  else:
3172  value = self.__class__(int=value, length=stop - start)
3173  stop = min(stop, self.len)
3174  start = max(start, 0)
3175  start = min(start, stop)
3176  if (stop - start) == value.len:
3177  if not value.len:
3178  return
3179  if step >= 0:
3180  self._overwrite(value, start)
3181  else:
3182  self._overwrite(value.__getitem__(slice(None, None, 1)), start)
3183  else:
3184  # TODO: A delete then insert is wasteful - it could do unneeded shifts.
3185  # Could be either overwrite + insert or overwrite + delete.
3186  self._delete(stop - start, start)
3187  if step >= 0:
3188  self._insert(value, start)
3189  else:
3190  self._insert(value.__getitem__(slice(None, None, 1)), start)
3191  # pos is now after the inserted piece.
3192  return
3193 
3194  def __delitem__(self, key):
3195  """Delete item or range.
3196 
3197  Indices are in units of the step parameter (default 1 bit).
3198  Stepping is used to specify the number of bits in each item.
3199 
3200  >>> a = BitArray('0x001122')
3201  >>> del a[1:2:8]
3202  >>> print a
3203  0x0022
3204 
3205  """
3206  try:
3207  # A slice
3208  start = 0
3209  step = key.step if key.step is not None else 1
3210  except AttributeError:
3211  # single element
3212  if key < 0:
3213  key += self.len
3214  if not 0 <= key < self.len:
3215  raise IndexError("Slice index out of range.")
3216  self._delete(1, key)
3217  return
3218  else:
3219  if step != 1:
3220  # convert to binary string and use string slicing
3221  # TODO: Horribly inefficent
3222  temp = list(self._getbin())
3223  temp.__delitem__(key)
3224  self._setbin_unsafe(''.join(temp))
3225  return
3226  stop = key.stop
3227  if key.start is not None:
3228  start = key.start
3229  if key.start < 0 and stop is None:
3230  start += self.len
3231  if start < 0:
3232  start = 0
3233  if stop is None:
3234  stop = self.len
3235  if start > stop:
3236  return
3237  stop = min(stop, self.len)
3238  start = max(start, 0)
3239  start = min(start, stop)
3240  self._delete(stop - start, start)
3241  return
3242 
3243  def __ilshift__(self, n):
3244  """Shift bits by n to the left in place. Return self.
3245 
3246  n -- the number of bits to shift. Must be >= 0.
3247 
3248  """
3249  if n < 0:
3250  raise ValueError("Cannot shift by a negative amount.")
3251  if not self.len:
3252  raise ValueError("Cannot shift an empty bitstring.")
3253  if not n:
3254  return self
3255  n = min(n, self.len)
3256  return self._ilshift(n)
3257 
3258  def __irshift__(self, n):
3259  """Shift bits by n to the right in place. Return self.
3260 
3261  n -- the number of bits to shift. Must be >= 0.
3262 
3263  """
3264  if n < 0:
3265  raise ValueError("Cannot shift by a negative amount.")
3266  if not self.len:
3267  raise ValueError("Cannot shift an empty bitstring.")
3268  if not n:
3269  return self
3270  n = min(n, self.len)
3271  return self._irshift(n)
3272 
3273  def __imul__(self, n):
3274  """Concatenate n copies of self in place. Return self.
3275 
3276  Called for expressions of the form 'a *= 3'.
3277  n -- The number of concatenations. Must be >= 0.
3278 
3279  """
3280  if n < 0:
3281  raise ValueError("Cannot multiply by a negative integer.")
3282  return self._imul(n)
3283 
3284  def __ior__(self, bs):
3285  bs = Bits(bs)
3286  if self.len != bs.len:
3287  raise ValueError("Bitstrings must have the same length "
3288  "for |= operator.")
3289  return self._ior(bs)
3290 
3291  def __iand__(self, bs):
3292  bs = Bits(bs)
3293  if self.len != bs.len:
3294  raise ValueError("Bitstrings must have the same length "
3295  "for &= operator.")
3296  return self._iand(bs)
3297 
3298  def __ixor__(self, bs):
3299  bs = Bits(bs)
3300  if self.len != bs.len:
3301  raise ValueError("Bitstrings must have the same length "
3302  "for ^= operator.")
3303  return self._ixor(bs)
3304 
3305  def replace(self, old, new, start=None, end=None, count=None,
3306  bytealigned=None):
3307  """Replace all occurrences of old with new in place.
3308 
3309  Returns number of replacements made.
3310 
3311  old -- The bitstring to replace.
3312  new -- The replacement bitstring.
3313  start -- Any occurrences that start before this will not be replaced.
3314  Defaults to 0.
3315  end -- Any occurrences that finish after this will not be replaced.
3316  Defaults to self.len.
3317  count -- The maximum number of replacements to make. Defaults to
3318  replace all occurrences.
3319  bytealigned -- If True replacements will only be made on byte
3320  boundaries.
3321 
3322  Raises ValueError if old is empty or if start or end are
3323  out of range.
3324 
3325  """
3326  old = Bits(old)
3327  new = Bits(new)
3328  if not old.len:
3329  raise ValueError("Empty bitstring cannot be replaced.")
3330  start, end = self._validate_slice(start, end)
3331  if bytealigned is None:
3332  bytealigned = globals()['bytealigned']
3333  # Adjust count for use in split()
3334  if count is not None:
3335  count += 1
3336  sections = self.split(old, start, end, count, bytealigned)
3337  lengths = [s.len for s in sections]
3338  if len(lengths) == 1:
3339  # Didn't find anything to replace.
3340  return 0 # no replacements done
3341  if new is self:
3342  # Prevent self assignment woes
3343  new = copy.copy(self)
3344  positions = [lengths[0] + start]
3345  for l in lengths[1:-1]:
3346  # Next position is the previous one plus the length of the next section.
3347  positions.append(positions[-1] + l)
3348  # We have all the positions that need replacements. We do them
3349  # in reverse order so that they won't move around as we replace.
3350  positions.reverse()
3351  try:
3352  # Need to calculate new pos, if this is a bitstream
3353  newpos = self._pos
3354  for p in positions:
3355  self[p:p + old.len] = new
3356  if old.len != new.len:
3357  diff = new.len - old.len
3358  for p in positions:
3359  if p >= newpos:
3360  continue
3361  if p + old.len <= newpos:
3362  newpos += diff
3363  else:
3364  newpos = p
3365  self._pos = newpos
3366  except AttributeError:
3367  for p in positions:
3368  self[p:p + old.len] = new
3369  assert self._assertsanity()
3370  return len(lengths) - 1
3371 
3372  def insert(self, bs, pos=None):
3373  """Insert bs at bit position pos.
3374 
3375  bs -- The bitstring to insert.
3376  pos -- The bit position to insert at.
3377 
3378  Raises ValueError if pos < 0 or pos > self.len.
3379 
3380  """
3381  bs = Bits(bs)
3382  if not bs.len:
3383  return self
3384  if bs is self:
3385  bs = self.__copy__()
3386  if pos is None:
3387  try:
3388  pos = self._pos
3389  except AttributeError:
3390  raise TypeError("insert require a bit position for this type.")
3391  if pos < 0:
3392  pos += self.len
3393  if not 0 <= pos <= self.len:
3394  raise ValueError("Invalid insert position.")
3395  self._insert(bs, pos)
3396 
3397  def overwrite(self, bs, pos=None):
3398  """Overwrite with bs at bit position pos.
3399 
3400  bs -- The bitstring to overwrite with.
3401  pos -- The bit position to begin overwriting from.
3402 
3403  Raises ValueError if pos < 0 or pos + bs.len > self.len
3404 
3405  """
3406  bs = Bits(bs)
3407  if not bs.len:
3408  return
3409  if pos is None:
3410  try:
3411  pos = self._pos
3412  except AttributeError:
3413  raise TypeError("overwrite require a bit position for this type.")
3414  if pos < 0:
3415  pos += self.len
3416  if pos < 0 or pos + bs.len > self.len:
3417  raise ValueError("Overwrite exceeds boundary of bitstring.")
3418  self._overwrite(bs, pos)
3419  try:
3420  self._pos = pos + bs.len
3421  except AttributeError:
3422  pass
3423 
3424  def append(self, bs):
3425  """Append a bitstring to the current bitstring.
3426 
3427  bs -- The bitstring to append.
3428 
3429  """
3430  # The offset is a hint to make bs easily appendable.
3431  bs = self._converttobitstring(bs, offset=(self.len + self._offset) % 8)
3432  self._append(bs)
3433 
3434  def prepend(self, bs):
3435  """Prepend a bitstring to the current bitstring.
3436 
3437  bs -- The bitstring to prepend.
3438 
3439  """
3440  bs = Bits(bs)
3441  self._prepend(bs)
3442 
3443  def reverse(self, start=None, end=None):
3444  """Reverse bits in-place.
3445 
3446  start -- Position of first bit to reverse. Defaults to 0.
3447  end -- One past the position of the last bit to reverse.
3448  Defaults to self.len.
3449 
3450  Using on an empty bitstring will have no effect.
3451 
3452  Raises ValueError if start < 0, end > self.len or end < start.
3453 
3454  """
3455  start, end = self._validate_slice(start, end)
3456  if start == 0 and end == self.len:
3457  self._reverse()
3458  return
3459  s = self._slice(start, end)
3460  s._reverse()
3461  self[start:end] = s
3462 
3463  def set(self, value, pos=None):
3464  """Set one or many bits to 1 or 0.
3465 
3466  value -- If True bits are set to 1, otherwise they are set to 0.
3467  pos -- Either a single bit position or an iterable of bit positions.
3468  Negative numbers are treated in the same way as slice indices.
3469  Defaults to the entire bitstring.
3470 
3471  Raises IndexError if pos < -self.len or pos >= self.len.
3472 
3473  """
3474  f = self._set if value else self._unset
3475  if pos is None:
3476  pos = xrange(self.len)
3477  try:
3478  length = self.len
3479  for p in pos:
3480  if p < 0:
3481  p += length
3482  if not 0 <= p < length:
3483  raise IndexError("Bit position {0} out of range.".format(p))
3484  f(p)
3485  except TypeError:
3486  # Single pos
3487  if pos < 0:
3488  pos += self.len
3489  if not 0 <= pos < length:
3490  raise IndexError("Bit position {0} out of range.".format(pos))
3491  f(pos)
3492 
3493  def invert(self, pos=None):
3494  """Invert one or many bits from 0 to 1 or vice versa.
3495 
3496  pos -- Either a single bit position or an iterable of bit positions.
3497  Negative numbers are treated in the same way as slice indices.
3498 
3499  Raises IndexError if pos < -self.len or pos >= self.len.
3500 
3501  """
3502  if pos is None:
3503  self._invert_all()
3504  return
3505  if not isinstance(pos, collections.Iterable):
3506  pos = (pos,)
3507  length = self.len
3508 
3509  for p in pos:
3510  if p < 0:
3511  p += length
3512  if not 0 <= p < length:
3513  raise IndexError("Bit position {0} out of range.".format(p))
3514  self._invert(p)
3515 
3516  def ror(self, bits, start=None, end=None):
3517  """Rotate bits to the right in-place.
3518 
3519  bits -- The number of bits to rotate by.
3520  start -- Start of slice to rotate. Defaults to 0.
3521  end -- End of slice to rotate. Defaults to self.len.
3522 
3523  Raises ValueError if bits < 0.
3524 
3525  """
3526  if not self.len:
3527  raise Error("Cannot rotate an empty bitstring.")
3528  if bits < 0:
3529  raise ValueError("Cannot rotate right by negative amount.")
3530  start, end = self._validate_slice(start, end)
3531  bits %= (end - start)
3532  if not bits:
3533  return
3534  rhs = self._slice(end - bits, end)
3535  self._delete(bits, end - bits)
3536  self._insert(rhs, start)
3537 
3538  def rol(self, bits, start=None, end=None):
3539  """Rotate bits to the left in-place.
3540 
3541  bits -- The number of bits to rotate by.
3542  start -- Start of slice to rotate. Defaults to 0.
3543  end -- End of slice to rotate. Defaults to self.len.
3544 
3545  Raises ValueError if bits < 0.
3546 
3547  """
3548  if not self.len:
3549  raise Error("Cannot rotate an empty bitstring.")
3550  if bits < 0:
3551  raise ValueError("Cannot rotate left by negative amount.")
3552  start, end = self._validate_slice(start, end)
3553  bits %= (end - start)
3554  if not bits:
3555  return
3556  lhs = self._slice(start, start + bits)
3557  self._delete(bits, start)
3558  self._insert(lhs, end - bits)
3559 
3560  def byteswap(self, fmt=None, start=None, end=None, repeat=True):
3561  """Change the endianness in-place. Return number of repeats of fmt done.
3562 
3563  fmt -- A compact structure string, an integer number of bytes or
3564  an iterable of integers. Defaults to 0, which byte reverses the
3565  whole bitstring.
3566  start -- Start bit position, defaults to 0.
3567  end -- End bit position, defaults to self.len.
3568  repeat -- If True (the default) the byte swapping pattern is repeated
3569  as much as possible.
3570 
3571  """
3572  start, end = self._validate_slice(start, end)
3573  if fmt is None or fmt == 0:
3574  # reverse all of the whole bytes.
3575  bytesizes = [(end - start) // 8]
3576  elif isinstance(fmt, numbers.Integral):
3577  if fmt < 0:
3578  raise ValueError("Improper byte length {0}.".format(fmt))
3579  bytesizes = [fmt]
3580  elif isinstance(fmt, basestring):
3581  m = STRUCT_PACK_RE.match(fmt)
3582  if not m:
3583  raise ValueError("Cannot parse format string {0}.".format(fmt))
3584  # Split the format string into a list of 'q', '4h' etc.
3585  formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt'))
3586  # Now deal with multiplicative factors, 4h -> hhhh etc.
3587  bytesizes = []
3588  for f in formatlist:
3589  if len(f) == 1:
3590  bytesizes.append(PACK_CODE_SIZE[f])
3591  else:
3592  bytesizes.extend([PACK_CODE_SIZE[f[-1]]] * int(f[:-1]))
3593  elif isinstance(fmt, collections.Iterable):
3594  bytesizes = fmt
3595  for bytesize in bytesizes:
3596  if not isinstance(bytesize, numbers.Integral) or bytesize < 0:
3597  raise ValueError("Improper byte length {0}.".format(bytesize))
3598  else:
3599  raise TypeError("Format must be an integer, string or iterable.")
3600 
3601  repeats = 0
3602  totalbitsize = 8 * sum(bytesizes)
3603  if not totalbitsize:
3604  return 0
3605  if repeat:
3606  # Try to repeat up to the end of the bitstring.
3607  finalbit = end
3608  else:
3609  # Just try one (set of) byteswap(s).
3610  finalbit = start + totalbitsize
3611  for patternend in xrange(start + totalbitsize, finalbit + 1, totalbitsize):
3612  bytestart = patternend - totalbitsize
3613  for bytesize in bytesizes:
3614  byteend = bytestart + bytesize * 8
3615  self._reversebytes(bytestart, byteend)
3616  bytestart += bytesize * 8
3617  repeats += 1
3618  return repeats
3619 
3620  def clear(self):
3621  """Remove all bits, reset to zero length."""
3622  self._clear()
3623 
3624  def copy(self):
3625  """Return a copy of the bitstring."""
3626  return self._copy()
3627 
3628  int = property(Bits._getint, Bits._setint,
3629  doc="""The bitstring as a two's complement signed int. Read and write.
3630  """)
3631  uint = property(Bits._getuint, Bits._setuint,
3632  doc="""The bitstring as a two's complement unsigned int. Read and write.
3633  """)
3634  float = property(Bits._getfloat, Bits._setfloat,
3635  doc="""The bitstring as a floating point number. Read and write.
3636  """)
3637  intbe = property(Bits._getintbe, Bits._setintbe,
3638  doc="""The bitstring as a two's complement big-endian signed int. Read and write.
3639  """)
3640  uintbe = property(Bits._getuintbe, Bits._setuintbe,
3641  doc="""The bitstring as a two's complement big-endian unsigned int. Read and write.
3642  """)
3643  floatbe = property(Bits._getfloat, Bits._setfloat,
3644  doc="""The bitstring as a big-endian floating point number. Read and write.
3645  """)
3646  intle = property(Bits._getintle, Bits._setintle,
3647  doc="""The bitstring as a two's complement little-endian signed int. Read and write.
3648  """)
3649  uintle = property(Bits._getuintle, Bits._setuintle,
3650  doc="""The bitstring as a two's complement little-endian unsigned int. Read and write.
3651  """)
3652  floatle = property(Bits._getfloatle, Bits._setfloatle,
3653  doc="""The bitstring as a little-endian floating point number. Read and write.
3654  """)
3655  intne = property(Bits._getintne, Bits._setintne,
3656  doc="""The bitstring as a two's complement native-endian signed int. Read and write.
3657  """)
3658  uintne = property(Bits._getuintne, Bits._setuintne,
3659  doc="""The bitstring as a two's complement native-endian unsigned int. Read and write.
3660  """)
3661  floatne = property(Bits._getfloatne, Bits._setfloatne,
3662  doc="""The bitstring as a native-endian floating point number. Read and write.
3663  """)
3664  ue = property(Bits._getue, Bits._setue,
3665  doc="""The bitstring as an unsigned exponential-Golomb code. Read and write.
3666  """)
3667  se = property(Bits._getse, Bits._setse,
3668  doc="""The bitstring as a signed exponential-Golomb code. Read and write.
3669  """)
3670  uie = property(Bits._getuie, Bits._setuie,
3671  doc="""The bitstring as an unsigned interleaved exponential-Golomb code. Read and write.
3672  """)
3673  sie = property(Bits._getsie, Bits._setsie,
3674  doc="""The bitstring as a signed interleaved exponential-Golomb code. Read and write.
3675  """)
3676  hex = property(Bits._gethex, Bits._sethex,
3677  doc="""The bitstring as a hexadecimal string. Read and write.
3678  """)
3679  bin = property(Bits._getbin, Bits._setbin_safe,
3680  doc="""The bitstring as a binary string. Read and write.
3681  """)
3682  oct = property(Bits._getoct, Bits._setoct,
3683  doc="""The bitstring as an octal string. Read and write.
3684  """)
3685  bool = property(Bits._getbool, Bits._setbool,
3686  doc="""The bitstring as a bool (True or False). Read and write.
3687  """)
3688  bytes = property(Bits._getbytes, Bits._setbytes_safe,
3689  doc="""The bitstring as a ordinary string. Read and write.
3690  """)
3691 
3692 
3694  """A container or stream holding an immutable sequence of bits.
3695 
3696  For a mutable container use the BitStream class instead.
3697 
3698  Methods inherited from Bits:
3699 
3700  all() -- Check if all specified bits are set to 1 or 0.
3701  any() -- Check if any of specified bits are set to 1 or 0.
3702  count() -- Count the number of bits set to 1 or 0.
3703  cut() -- Create generator of constant sized chunks.
3704  endswith() -- Return whether the bitstring ends with a sub-string.
3705  find() -- Find a sub-bitstring in the current bitstring.
3706  findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
3707  join() -- Join bitstrings together using current bitstring.
3708  rfind() -- Seek backwards to find a sub-bitstring.
3709  split() -- Create generator of chunks split by a delimiter.
3710  startswith() -- Return whether the bitstring starts with a sub-bitstring.
3711  tobytes() -- Return bitstring as bytes, padding if needed.
3712  tofile() -- Write bitstring to file, padding if needed.
3713  unpack() -- Interpret bits using format string.
3714 
3715  Other methods:
3716 
3717  bytealign() -- Align to next byte boundary.
3718  peek() -- Peek at and interpret next bits as a single item.
3719  peeklist() -- Peek at and interpret next bits as a list of items.
3720  read() -- Read and interpret next bits as a single item.
3721  readlist() -- Read and interpret next bits as a list of items.
3722 
3723  Special methods:
3724 
3725  Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^.
3726 
3727  Properties:
3728 
3729  bin -- The bitstring as a binary string.
3730  bool -- For single bit bitstrings, interpret as True or False.
3731  bytepos -- The current byte position in the bitstring.
3732  bytes -- The bitstring as a bytes object.
3733  float -- Interpret as a floating point number.
3734  floatbe -- Interpret as a big-endian floating point number.
3735  floatle -- Interpret as a little-endian floating point number.
3736  floatne -- Interpret as a native-endian floating point number.
3737  hex -- The bitstring as a hexadecimal string.
3738  int -- Interpret as a two's complement signed integer.
3739  intbe -- Interpret as a big-endian signed integer.
3740  intle -- Interpret as a little-endian signed integer.
3741  intne -- Interpret as a native-endian signed integer.
3742  len -- Length of the bitstring in bits.
3743  oct -- The bitstring as an octal string.
3744  pos -- The current bit position in the bitstring.
3745  se -- Interpret as a signed exponential-Golomb code.
3746  ue -- Interpret as an unsigned exponential-Golomb code.
3747  sie -- Interpret as a signed interleaved exponential-Golomb code.
3748  uie -- Interpret as an unsigned interleaved exponential-Golomb code.
3749  uint -- Interpret as a two's complement unsigned integer.
3750  uintbe -- Interpret as a big-endian unsigned integer.
3751  uintle -- Interpret as a little-endian unsigned integer.
3752  uintne -- Interpret as a native-endian unsigned integer.
3753 
3754  """
3755 
3756  __slots__ = ('_pos')
3757 
3758  def __init__(self, auto=None, length=None, offset=None, **kwargs):
3759  """Either specify an 'auto' initialiser:
3760  auto -- a string of comma separated tokens, an integer, a file object,
3761  a bytearray, a boolean iterable or another bitstring.
3762 
3763  Or initialise via **kwargs with one (and only one) of:
3764  bytes -- raw data as a string, for example read from a binary file.
3765  bin -- binary string representation, e.g. '0b001010'.
3766  hex -- hexadecimal string representation, e.g. '0x2ef'
3767  oct -- octal string representation, e.g. '0o777'.
3768  uint -- an unsigned integer.
3769  int -- a signed integer.
3770  float -- a floating point number.
3771  uintbe -- an unsigned big-endian whole byte integer.
3772  intbe -- a signed big-endian whole byte integer.
3773  floatbe - a big-endian floating point number.
3774  uintle -- an unsigned little-endian whole byte integer.
3775  intle -- a signed little-endian whole byte integer.
3776  floatle -- a little-endian floating point number.
3777  uintne -- an unsigned native-endian whole byte integer.
3778  intne -- a signed native-endian whole byte integer.
3779  floatne -- a native-endian floating point number.
3780  se -- a signed exponential-Golomb code.
3781  ue -- an unsigned exponential-Golomb code.
3782  sie -- a signed interleaved exponential-Golomb code.
3783  uie -- an unsigned interleaved exponential-Golomb code.
3784  bool -- a boolean (True or False).
3785  filename -- a file which will be opened in binary read-only mode.
3786 
3787  Other keyword arguments:
3788  length -- length of the bitstring in bits, if needed and appropriate.
3789  It must be supplied for all integer and float initialisers.
3790  offset -- bit offset to the data. These offset bits are
3791  ignored and this is intended for use when
3792  initialising using 'bytes' or 'filename'.
3793 
3794  """
3795  self._pos = 0
3796 
3797  def __new__(cls, auto=None, length=None, offset=None, **kwargs):
3798  x = super(ConstBitStream, cls).__new__(cls)
3799  x._initialise(auto, length, offset, **kwargs)
3800  return x
3801 
3802  def _setbytepos(self, bytepos):
3803  """Move to absolute byte-aligned position in stream."""
3804  self._setbitpos(bytepos * 8)
3805 
3806  def _getbytepos(self):
3807  """Return the current position in the stream in bytes. Must be byte aligned."""
3808  if self._pos % 8:
3809  raise ByteAlignError("Not byte aligned in _getbytepos().")
3810  return self._pos // 8
3811 
3812  def _setbitpos(self, pos):
3813  """Move to absolute postion bit in bitstream."""
3814  if pos < 0:
3815  raise ValueError("Bit position cannot be negative.")
3816  if pos > self.len:
3817  raise ValueError("Cannot seek past the end of the data.")
3818  self._pos = pos
3819 
3820  def _getbitpos(self):
3821  """Return the current position in the stream in bits."""
3822  return self._pos
3823 
3824  def _clear(self):
3825  Bits._clear(self)
3826  self._pos = 0
3827 
3828  def __copy__(self):
3829  """Return a new copy of the ConstBitStream for the copy module."""
3830  # Note that if you want a new copy (different ID), use _copy instead.
3831  # The copy can use the same datastore as it's immutable.
3832  s = ConstBitStream()
3833  s._datastore = self._datastore
3834  # Reset the bit position, don't copy it.
3835  s._pos = 0
3836  return s
3837 
3838  def __add__(self, bs):
3839  """Concatenate bitstrings and return new bitstring.
3840 
3841  bs -- the bitstring to append.
3842 
3843  """
3844  s = Bits.__add__(self, bs)
3845  s._pos = 0
3846  return s
3847 
3848  def read(self, fmt):
3849  """Interpret next bits according to the format string and return result.
3850 
3851  fmt -- Token string describing how to interpret the next bits.
3852 
3853  Token examples: 'int:12' : 12 bits as a signed integer
3854  'uint:8' : 8 bits as an unsigned integer
3855  'float:64' : 8 bytes as a big-endian float
3856  'intbe:16' : 2 bytes as a big-endian signed integer
3857  'uintbe:16' : 2 bytes as a big-endian unsigned integer
3858  'intle:32' : 4 bytes as a little-endian signed integer
3859  'uintle:32' : 4 bytes as a little-endian unsigned integer
3860  'floatle:64': 8 bytes as a little-endian float
3861  'intne:24' : 3 bytes as a native-endian signed integer
3862  'uintne:24' : 3 bytes as a native-endian unsigned integer
3863  'floatne:32': 4 bytes as a native-endian float
3864  'hex:80' : 80 bits as a hex string
3865  'oct:9' : 9 bits as an octal string
3866  'bin:1' : single bit binary string
3867  'ue' : next bits as unsigned exp-Golomb code
3868  'se' : next bits as signed exp-Golomb code
3869  'uie' : next bits as unsigned interleaved exp-Golomb code
3870  'sie' : next bits as signed interleaved exp-Golomb code
3871  'bits:5' : 5 bits as a bitstring
3872  'bytes:10' : 10 bytes as a bytes object
3873  'bool' : 1 bit as a bool
3874  'pad:3' : 3 bits of padding to ignore - returns None
3875 
3876  fmt may also be an integer, which will be treated like the 'bits' token.
3877 
3878  The position in the bitstring is advanced to after the read items.
3879 
3880  Raises ReadError if not enough bits are available.
3881  Raises ValueError if the format is not understood.
3882 
3883  """
3884  if isinstance(fmt, numbers.Integral):
3885  if fmt < 0:
3886  raise ValueError("Cannot read negative amount.")
3887  if fmt > self.len - self._pos:
3888  raise ReadError("Cannot read {0} bits, only {1} available.",
3889  fmt, self.len - self._pos)
3890  bs = self._slice(self._pos, self._pos + fmt)
3891  self._pos += fmt
3892  return bs
3893  p = self._pos
3894  _, token = tokenparser(fmt)
3895  if len(token) != 1:
3896  self._pos = p
3897  raise ValueError("Format string should be a single token, not {0} "
3898  "tokens - use readlist() instead.".format(len(token)))
3899  name, length, _ = token[0]
3900  if length is None:
3901  length = self.len - self._pos
3902  value, self._pos = self._readtoken(name, self._pos, length)
3903  return value
3904 
3905  def readlist(self, fmt, **kwargs):
3906  """Interpret next bits according to format string(s) and return list.
3907 
3908  fmt -- A single string or list of strings with comma separated tokens
3909  describing how to interpret the next bits in the bitstring. Items
3910  can also be integers, for reading new bitstring of the given length.
3911  kwargs -- A dictionary or keyword-value pairs - the keywords used in the
3912  format string will be replaced with their given value.
3913 
3914  The position in the bitstring is advanced to after the read items.
3915 
3916  Raises ReadError is not enough bits are available.
3917  Raises ValueError if the format is not understood.
3918 
3919  See the docstring for 'read' for token examples. 'pad' tokens are skipped
3920  and not added to the returned list.
3921 
3922  >>> h, b1, b2 = s.readlist('hex:20, bin:5, bin:3')
3923  >>> i, bs1, bs2 = s.readlist(['uint:12', 10, 10])
3924 
3925  """
3926  value, self._pos = self._readlist(fmt, self._pos, **kwargs)
3927  return value
3928 
3929  def readto(self, bs, bytealigned=None):
3930  """Read up to and including next occurrence of bs and return result.
3931 
3932  bs -- The bitstring to find. An integer is not permitted.
3933  bytealigned -- If True the bitstring will only be
3934  found on byte boundaries.
3935 
3936  Raises ValueError if bs is empty.
3937  Raises ReadError if bs is not found.
3938 
3939  """
3940  if isinstance(bs, numbers.Integral):
3941  raise ValueError("Integers cannot be searched for")
3942  bs = Bits(bs)
3943  oldpos = self._pos
3944  p = self.find(bs, self._pos, bytealigned=bytealigned)
3945  if not p:
3946  raise ReadError("Substring not found")
3947  self._pos += bs.len
3948  return self._slice(oldpos, self._pos)
3949 
3950  def peek(self, fmt):
3951  """Interpret next bits according to format string and return result.
3952 
3953  fmt -- Token string describing how to interpret the next bits.
3954 
3955  The position in the bitstring is not changed. If not enough bits are
3956  available then all bits to the end of the bitstring will be used.
3957 
3958  Raises ReadError if not enough bits are available.
3959  Raises ValueError if the format is not understood.
3960 
3961  See the docstring for 'read' for token examples.
3962 
3963  """
3964  pos_before = self._pos
3965  value = self.read(fmt)
3966  self._pos = pos_before
3967  return value
3968 
3969  def peeklist(self, fmt, **kwargs):
3970  """Interpret next bits according to format string(s) and return list.
3971 
3972  fmt -- One or more strings with comma separated tokens describing
3973  how to interpret the next bits in the bitstring.
3974  kwargs -- A dictionary or keyword-value pairs - the keywords used in the
3975  format string will be replaced with their given value.
3976 
3977  The position in the bitstring is not changed. If not enough bits are
3978  available then all bits to the end of the bitstring will be used.
3979 
3980  Raises ReadError if not enough bits are available.
3981  Raises ValueError if the format is not understood.
3982 
3983  See the docstring for 'read' for token examples.
3984 
3985  """
3986  pos = self._pos
3987  return_values = self.readlist(fmt, **kwargs)
3988  self._pos = pos
3989  return return_values
3990 
3991  def bytealign(self):
3992  """Align to next byte and return number of skipped bits.
3993 
3994  Raises ValueError if the end of the bitstring is reached before
3995  aligning to the next byte.
3996 
3997  """
3998  skipped = (8 - (self._pos % 8)) % 8
3999  self.pos += self._offset + skipped
4000  assert self._assertsanity()
4001  return skipped
4002 
4003  pos = property(_getbitpos, _setbitpos,
4004  doc="""The position in the bitstring in bits. Read and write.
4005  """)
4006  bitpos = property(_getbitpos, _setbitpos,
4007  doc="""The position in the bitstring in bits. Read and write.
4008  """)
4009  bytepos = property(_getbytepos, _setbytepos,
4010  doc="""The position in the bitstring in bytes. Read and write.
4011  """)
4012 
4013 
4015  """A container or stream holding a mutable sequence of bits
4016 
4017  Subclass of the ConstBitStream and BitArray classes. Inherits all of
4018  their methods.
4019 
4020  Methods:
4021 
4022  all() -- Check if all specified bits are set to 1 or 0.
4023  any() -- Check if any of specified bits are set to 1 or 0.
4024  append() -- Append a bitstring.
4025  bytealign() -- Align to next byte boundary.
4026  byteswap() -- Change byte endianness in-place.
4027  count() -- Count the number of bits set to 1 or 0.
4028  cut() -- Create generator of constant sized chunks.
4029  endswith() -- Return whether the bitstring ends with a sub-string.
4030  find() -- Find a sub-bitstring in the current bitstring.
4031  findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
4032  insert() -- Insert a bitstring.
4033  invert() -- Flip bit(s) between one and zero.
4034  join() -- Join bitstrings together using current bitstring.
4035  overwrite() -- Overwrite a section with a new bitstring.
4036  peek() -- Peek at and interpret next bits as a single item.
4037  peeklist() -- Peek at and interpret next bits as a list of items.
4038  prepend() -- Prepend a bitstring.
4039  read() -- Read and interpret next bits as a single item.
4040  readlist() -- Read and interpret next bits as a list of items.
4041  replace() -- Replace occurrences of one bitstring with another.
4042  reverse() -- Reverse bits in-place.
4043  rfind() -- Seek backwards to find a sub-bitstring.
4044  rol() -- Rotate bits to the left.
4045  ror() -- Rotate bits to the right.
4046  set() -- Set bit(s) to 1 or 0.
4047  split() -- Create generator of chunks split by a delimiter.
4048  startswith() -- Return whether the bitstring starts with a sub-bitstring.
4049  tobytes() -- Return bitstring as bytes, padding if needed.
4050  tofile() -- Write bitstring to file, padding if needed.
4051  unpack() -- Interpret bits using format string.
4052 
4053  Special methods:
4054 
4055  Mutating operators are available: [], <<=, >>=, +=, *=, &=, |= and ^=
4056  in addition to [], ==, !=, +, *, ~, <<, >>, &, | and ^.
4057 
4058  Properties:
4059 
4060  bin -- The bitstring as a binary string.
4061  bool -- For single bit bitstrings, interpret as True or False.
4062  bytepos -- The current byte position in the bitstring.
4063  bytes -- The bitstring as a bytes object.
4064  float -- Interpret as a floating point number.
4065  floatbe -- Interpret as a big-endian floating point number.
4066  floatle -- Interpret as a little-endian floating point number.
4067  floatne -- Interpret as a native-endian floating point number.
4068  hex -- The bitstring as a hexadecimal string.
4069  int -- Interpret as a two's complement signed integer.
4070  intbe -- Interpret as a big-endian signed integer.
4071  intle -- Interpret as a little-endian signed integer.
4072  intne -- Interpret as a native-endian signed integer.
4073  len -- Length of the bitstring in bits.
4074  oct -- The bitstring as an octal string.
4075  pos -- The current bit position in the bitstring.
4076  se -- Interpret as a signed exponential-Golomb code.
4077  ue -- Interpret as an unsigned exponential-Golomb code.
4078  sie -- Interpret as a signed interleaved exponential-Golomb code.
4079  uie -- Interpret as an unsigned interleaved exponential-Golomb code.
4080  uint -- Interpret as a two's complement unsigned integer.
4081  uintbe -- Interpret as a big-endian unsigned integer.
4082  uintle -- Interpret as a little-endian unsigned integer.
4083  uintne -- Interpret as a native-endian unsigned integer.
4084 
4085  """
4086 
4087  __slots__ = ()
4088 
4089  # As BitStream objects are mutable, we shouldn't allow them to be hashed.
4090  __hash__ = None
4091 
4092  def __init__(self, auto=None, length=None, offset=None, **kwargs):
4093  """Either specify an 'auto' initialiser:
4094  auto -- a string of comma separated tokens, an integer, a file object,
4095  a bytearray, a boolean iterable or another bitstring.
4096 
4097  Or initialise via **kwargs with one (and only one) of:
4098  bytes -- raw data as a string, for example read from a binary file.
4099  bin -- binary string representation, e.g. '0b001010'.
4100  hex -- hexadecimal string representation, e.g. '0x2ef'
4101  oct -- octal string representation, e.g. '0o777'.
4102  uint -- an unsigned integer.
4103  int -- a signed integer.
4104  float -- a floating point number.
4105  uintbe -- an unsigned big-endian whole byte integer.
4106  intbe -- a signed big-endian whole byte integer.
4107  floatbe - a big-endian floating point number.
4108  uintle -- an unsigned little-endian whole byte integer.
4109  intle -- a signed little-endian whole byte integer.
4110  floatle -- a little-endian floating point number.
4111  uintne -- an unsigned native-endian whole byte integer.
4112  intne -- a signed native-endian whole byte integer.
4113  floatne -- a native-endian floating point number.
4114  se -- a signed exponential-Golomb code.
4115  ue -- an unsigned exponential-Golomb code.
4116  sie -- a signed interleaved exponential-Golomb code.
4117  uie -- an unsigned interleaved exponential-Golomb code.
4118  bool -- a boolean (True or False).
4119  filename -- a file which will be opened in binary read-only mode.
4120 
4121  Other keyword arguments:
4122  length -- length of the bitstring in bits, if needed and appropriate.
4123  It must be supplied for all integer and float initialisers.
4124  offset -- bit offset to the data. These offset bits are
4125  ignored and this is intended for use when
4126  initialising using 'bytes' or 'filename'.
4127 
4128  """
4129  self._pos = 0
4130  # For mutable BitStreams we always read in files to memory:
4131  if not isinstance(self._datastore, ByteStore):
4132  self._ensureinmemory()
4133 
4134  def __new__(cls, auto=None, length=None, offset=None, **kwargs):
4135  x = super(BitStream, cls).__new__(cls)
4136  x._initialise(auto, length, offset, **kwargs)
4137  return x
4138 
4139  def __copy__(self):
4140  """Return a new copy of the BitStream."""
4141  s_copy = BitStream()
4142  s_copy._pos = 0
4143  if not isinstance(self._datastore, ByteStore):
4144  # Let them both point to the same (invariant) array.
4145  # If either gets modified then at that point they'll be read into memory.
4146  s_copy._datastore = self._datastore
4147  else:
4148  s_copy._datastore = ByteStore(self._datastore._rawarray[:],
4149  self._datastore.bitlength,
4150  self._datastore.offset)
4151  return s_copy
4152 
4153  def prepend(self, bs):
4154  """Prepend a bitstring to the current bitstring.
4155 
4156  bs -- The bitstring to prepend.
4157 
4158  """
4159  bs = self._converttobitstring(bs)
4160  self._prepend(bs)
4161  self._pos += bs.len
4162 
4163 
4164 def pack(fmt, *values, **kwargs):
4165  """Pack the values according to the format string and return a new BitStream.
4166 
4167  fmt -- A single string or a list of strings with comma separated tokens
4168  describing how to create the BitStream.
4169  values -- Zero or more values to pack according to the format.
4170  kwargs -- A dictionary or keyword-value pairs - the keywords used in the
4171  format string will be replaced with their given value.
4172 
4173  Token examples: 'int:12' : 12 bits as a signed integer
4174  'uint:8' : 8 bits as an unsigned integer
4175  'float:64' : 8 bytes as a big-endian float
4176  'intbe:16' : 2 bytes as a big-endian signed integer
4177  'uintbe:16' : 2 bytes as a big-endian unsigned integer
4178  'intle:32' : 4 bytes as a little-endian signed integer
4179  'uintle:32' : 4 bytes as a little-endian unsigned integer
4180  'floatle:64': 8 bytes as a little-endian float
4181  'intne:24' : 3 bytes as a native-endian signed integer
4182  'uintne:24' : 3 bytes as a native-endian unsigned integer
4183  'floatne:32': 4 bytes as a native-endian float
4184  'hex:80' : 80 bits as a hex string
4185  'oct:9' : 9 bits as an octal string
4186  'bin:1' : single bit binary string
4187  'ue' / 'uie': next bits as unsigned exp-Golomb code
4188  'se' / 'sie': next bits as signed exp-Golomb code
4189  'bits:5' : 5 bits as a bitstring object
4190  'bytes:10' : 10 bytes as a bytes object
4191  'bool' : 1 bit as a bool
4192  'pad:3' : 3 zero bits as padding
4193 
4194  >>> s = pack('uint:12, bits', 100, '0xffe')
4195  >>> t = pack(['bits', 'bin:3'], s, '111')
4196  >>> u = pack('uint:8=a, uint:8=b, uint:55=a', a=6, b=44)
4197 
4198  """
4199  tokens = []
4200  if isinstance(fmt, basestring):
4201  fmt = [fmt]
4202  try:
4203  for f_item in fmt:
4204  _, tkns = tokenparser(f_item, tuple(sorted(kwargs.keys())))
4205  tokens.extend(tkns)
4206  except ValueError as e:
4207  raise CreationError(*e.args)
4208  value_iter = iter(values)
4209  s = BitStream()
4210  try:
4211  for name, length, value in tokens:
4212  # If the value is in the kwd dictionary then it takes precedence.
4213  if value in kwargs:
4214  value = kwargs[value]
4215  # If the length is in the kwd dictionary then use that too.
4216  if length in kwargs:
4217  length = kwargs[length]
4218  # Also if we just have a dictionary name then we want to use it
4219  if name in kwargs and length is None and value is None:
4220  s.append(kwargs[name])
4221  continue
4222  if length is not None:
4223  length = int(length)
4224  if value is None and name != 'pad':
4225  # Take the next value from the ones provided
4226  value = next(value_iter)
4227  s._append(BitStream._init_with_token(name, length, value))
4228  except StopIteration:
4229  raise CreationError("Not enough parameters present to pack according to the "
4230  "format. {0} values are needed.", len(tokens))
4231  try:
4232  next(value_iter)
4233  except StopIteration:
4234  # Good, we've used up all the *values.
4235  return s
4236  raise CreationError("Too many parameters present to pack according to the format.")
4237 
4238 
4239 # Aliases for backward compatibility
4240 ConstBitArray = Bits
4241 BitString = BitStream
4242 
4243 __all__ = ['ConstBitArray', 'ConstBitStream', 'BitStream', 'BitArray',
4244  'Bits', 'BitString', 'pack', 'Error', 'ReadError',
4245  'InterpretError', 'ByteAlignError', 'CreationError', 'bytealigned']
scripts.bitstring.Bits._invert
def _invert(self, pos)
Definition: bitstring.py:2178
scripts.bitstring.Bits.__init__
def __init__(self, auto=None, length=None, offset=None, **kwargs)
Definition: bitstring.py:739
scripts.bitstring.Bits._ensureinmemory
def _ensureinmemory(self)
Definition: bitstring.py:1956
scripts.bitstring.Bits._setuintbe
def _setuintbe(self, uintbe, length=None)
Definition: bitstring.py:1454
scripts.bitstring.Bits._readtoken
def _readtoken(self, name, pos, length)
Definition: bitstring.py:2013
scripts.bitstring.BitArray.insert
def insert(self, bs, pos=None)
Definition: bitstring.py:3372
scripts.bitstring.Bits._overwrite
def _overwrite(self, bs, pos)
Definition: bitstring.py:2096
scripts.bitstring.Bits._reversebytes
def _reversebytes(self, start, end)
Definition: bitstring.py:2155
scripts.bitstring.Bits.tobytes
def tobytes(self)
Definition: bitstring.py:2649
scripts.bitstring.Bits._readuintle
def _readuintle(self, length, start)
Definition: bitstring.py:1497
scripts.bitstring.Bits._slice
def _slice(self, start, end)
Definition: bitstring.py:2002
scripts.bitstring.ConstBitStream
Definition: bitstring.py:3693
scripts.bitstring.Bits._ior
def _ior(self, bs)
Definition: bitstring.py:2234
scripts.bitstring.Bits._unset
def _unset(self, pos)
Definition: bitstring.py:2173
scripts.bitstring.Bits._setfile
def _setfile(self, filename, length, offset)
Definition: bitstring.py:1306
scripts.bitstring.Bits.__copy__
def __copy__(self)
Definition: bitstring.py:846
scripts.bitstring.ConstBitStream._getbitpos
def _getbitpos(self)
Definition: bitstring.py:3820
scripts.bitstring.ConstBitStream.peek
def peek(self, fmt)
Definition: bitstring.py:3950
scripts.bitstring.ConstBitStream.bytealign
def bytealign(self)
Definition: bitstring.py:3991
scripts.bitstring.Bits._setbytes_unsafe
def _setbytes_unsafe(self, data, length, offset)
Definition: bitstring.py:1337
scripts.bitstring.Bits._converttobitstring
def _converttobitstring(cls, bs, offset=0, cache={})
Definition: bitstring.py:1962
scripts.bitstring.ByteStore
Definition: bitstring.py:220
scripts.bitstring.Bits.__lshift__
def __lshift__(self, n)
Definition: bitstring.py:1020
scripts.bitstring.Bits._getlength
def _getlength(self)
Definition: bitstring.py:1952
scripts.bitstring.Bits.startswith
def startswith(self, prefix, start=None, end=None)
Definition: bitstring.py:2696
scripts.bitstring.MmapByteArray.source
source
Definition: bitstring.py:404
scripts.bitstring.BitArray.invert
def invert(self, pos=None)
Definition: bitstring.py:3493
scripts.bitstring.Bits._getuintbe
def _getuintbe(self)
Definition: bitstring.py:1468
scripts.bitstring.Bits.__rxor__
def __rxor__(self, bs)
Definition: bitstring.py:1143
scripts.bitstring.Bits._getue
def _getue(self)
Definition: bitstring.py:1672
scripts.bitstring.ConstBitStream.read
def read(self, fmt)
Definition: bitstring.py:3848
scripts.bitstring.Bits._readfloatle
def _readfloatle(self, length, start)
Definition: bitstring.py:1602
scripts.bitstring.Bits._getbytes
def _getbytes(self)
Definition: bitstring.py:1351
scripts.bitstring.Bits.__rand__
def __rand__(self, bs)
Definition: bitstring.py:1091
scripts.bitstring.ConstBitStream.__copy__
def __copy__(self)
Definition: bitstring.py:3828
scripts.bitstring.BitArray.copy
def copy(self)
Definition: bitstring.py:3624
scripts.bitstring.Bits.__eq__
def __eq__(self, bs)
Definition: bitstring.py:986
scripts.bitstring.Bits._readintbe
def _readintbe(self, length, start)
Definition: bitstring.py:1479
scripts.bitstring.Bits._findregex
def _findregex(self, reg_ex, start, end, bytealigned)
Definition: bitstring.py:2386
scripts.bitstring.Bits._validate_slice
def _validate_slice(self, start, end)
Definition: bitstring.py:2247
scripts.bitstring.ConstBitStream.readlist
def readlist(self, fmt, **kwargs)
Definition: bitstring.py:3905
scripts.bitstring.Bits.__invert__
def __invert__(self)
Definition: bitstring.py:1008
scripts.bitstring.Bits._pos
_pos
Definition: bitstring.py:1166
scripts.bitstring.offsetcopy
def offsetcopy(s, newoffset)
Definition: bitstring.py:249
scripts.bitstring.Bits._getoct
def _getoct(self)
Definition: bitstring.py:1902
scripts.bitstring.Bits.__rmul__
def __rmul__(self, n)
Definition: bitstring.py:1066
scripts.bitstring.Bits._setoct
def _setoct(self, octstring)
Definition: bitstring.py:1872
scripts.bitstring.Bits._irshift
def _irshift(self, n)
Definition: bitstring.py:2197
scripts.bitstring.Bits._setbin_safe
def _setbin_safe(self, binstring)
Definition: bitstring.py:1830
scripts.bitstring.BitArray.__imul__
def __imul__(self, n)
Definition: bitstring.py:3273
scripts.bitstring.ConstByteStore.offset
offset
Definition: bitstring.py:146
scripts.bitstring.Bits.find
def find(self, bs, start=None, end=None, bytealigned=None)
Definition: bitstring.py:2418
scripts.bitstring.Bits.unpack
def unpack(self, fmt, **kwargs)
Definition: bitstring.py:2265
scripts.bitstring.Bits._setintbe
def _setintbe(self, intbe, length=None)
Definition: bitstring.py:1472
scripts.bitstring.BitArray.byteswap
def byteswap(self, fmt=None, start=None, end=None, repeat=True)
Definition: bitstring.py:3560
scripts.bitstring.Bits._ilshift
def _ilshift(self, n)
Definition: bitstring.py:2190
scripts.bitstring.Bits._readuintbe
def _readuintbe(self, length, start)
Definition: bitstring.py:1461
scripts.bitstring.Bits._readbin
def _readbin(self, length, start)
Definition: bitstring.py:1851
scripts.bitstring.ConstBitStream.__init__
def __init__(self, auto=None, length=None, offset=None, **kwargs)
Definition: bitstring.py:3758
scripts.bitstring.Bits._readse
def _readse(self, pos)
Definition: bitstring.py:1708
scripts.bitstring.Bits._getuie
def _getuie(self)
Definition: bitstring.py:1755
scripts.bitstring.BitArray.set
def set(self, value, pos=None)
Definition: bitstring.py:3463
scripts.bitstring.Bits.all
def all(self, value, pos=None)
Definition: bitstring.py:2726
scripts.bitstring.Bits._delete
def _delete(self, bits, pos)
Definition: bitstring.py:2129
scripts.bitstring.Bits.__hash__
def __hash__(self)
Definition: bitstring.py:1171
scripts.bitstring.Bits._getse
def _getse(self)
Definition: bitstring.py:1694
scripts.bitstring.Bits._readsie
def _readsie(self, pos)
Definition: bitstring.py:1791
scripts.bitstring.tokenparser
def tokenparser(fmt, keys=None, token_cache={})
Definition: bitstring.py:539
scripts.bitstring.Bits.__rshift__
def __rshift__(self, n)
Definition: bitstring.py:1035
scripts.bitstring.MmapByteArray
Definition: bitstring.py:395
scripts.bitstring.Bits._prepend
def _prepend(self, bs)
Definition: bitstring.py:2033
scripts.bitstring.Error
Definition: bitstring.py:90
scripts.bitstring.Bits._getfloatle
def _getfloatle(self)
Definition: bitstring.py:1621
scripts.bitstring.BitArray.__ilshift__
def __ilshift__(self, n)
Definition: bitstring.py:3243
scripts.bitstring.ConstByteStore.getbyte
def getbyte(self, pos)
Definition: bitstring.py:154
scripts.bitstring.equal
def equal(a, b)
Definition: bitstring.py:291
scripts.bitstring.Bits._truncatestart
def _truncatestart(self, bits)
Definition: bitstring.py:2049
scripts.bitstring.BitArray.rol
def rol(self, bits, start=None, end=None)
Definition: bitstring.py:3538
scripts.bitstring.ConstBitStream.readto
def readto(self, bs, bytealigned=None)
Definition: bitstring.py:3929
scripts.bitstring.Bits.__ror__
def __ror__(self, bs)
Definition: bitstring.py:1117
scripts.bitstring.Bits._getbin
def _getbin(self)
Definition: bitstring.py:1868
scripts.bitstring.ConstByteStore
Definition: bitstring.py:131
scripts.bitstring.BitStream.__copy__
def __copy__(self)
Definition: bitstring.py:4139
scripts.bitstring.Bits._set
def _set(self, pos)
Definition: bitstring.py:2168
scripts.bitstring.Bits._getsie
def _getsie(self)
Definition: bitstring.py:1777
scripts.bitstring.Bits._insert
def _insert(self, bs, pos)
Definition: bitstring.py:2075
scripts.bitstring.Bits._readuint
def _readuint(self, length, start)
Definition: bitstring.py:1395
scripts.bitstring.Bits.__or__
def __or__(self, bs)
Definition: bitstring.py:1101
scripts.bitstring.ConstBitStream._getbytepos
def _getbytepos(self)
Definition: bitstring.py:3806
scripts.bitstring.Bits.__contains__
def __contains__(self, bs)
Definition: bitstring.py:1153
scripts.bitstring.Bits._getuint
def _getuint(self)
Definition: bitstring.py:1413
scripts.bitstring.InterpretError
Definition: bitstring.py:110
scripts.bitstring.ReadError
Definition: bitstring.py:103
scripts.bitstring.BitStream.prepend
def prepend(self, bs)
Definition: bitstring.py:4153
scripts.bitstring.BitArray.overwrite
def overwrite(self, bs, pos=None)
Definition: bitstring.py:3397
scripts.bitstring.BitArray.replace
def replace(self, old, new, start=None, end=None, count=None, bytealigned=None)
Definition: bitstring.py:3305
scripts.bitstring.Bits._setsie
def _setsie(self, i)
Definition: bitstring.py:1769
scripts.bitstring.Bits._offset
_offset
Definition: bitstring.py:2815
scripts.bitstring.MmapByteArray.byteoffset
byteoffset
Definition: bitstring.py:411
scripts.bitstring.Bits.split
def split(self, delimiter, start=None, end=None, count=None, bytealigned=None)
Definition: bitstring.py:2574
scripts.bitstring.Bits.__radd__
def __radd__(self, bs)
Definition: bitstring.py:880
scripts.bitstring.ConstByteStore._prependstore
def _prependstore(self, store)
Definition: bitstring.py:190
scripts.bitstring.Bits.join
def join(self, sequence)
Definition: bitstring.py:2631
scripts.bitstring.Error.msg
msg
Definition: bitstring.py:94
scripts.bitstring.structparser
def structparser(token)
Definition: bitstring.py:510
scripts.bitstring.Bits._clear
def _clear(self)
Definition: bitstring.py:1248
scripts.bitstring.Bits._inplace_logical_helper
def _inplace_logical_helper(self, bs, f)
Definition: bitstring.py:2218
scripts.bitstring.CreationError
Definition: bitstring.py:124
scripts.bitstring.Bits._setse
def _setse(self, i)
Definition: bitstring.py:1686
scripts.bitstring.Bits._getint
def _getint(self)
Definition: bitstring.py:1450
scripts.bitstring.Bits._readoct
def _readoct(self, length, start)
Definition: bitstring.py:1887
scripts.bitstring.ConstBitStream._setbytepos
def _setbytepos(self, bytepos)
Definition: bitstring.py:3802
scripts.bitstring.Bits._copy
def _copy(self)
Definition: bitstring.py:1995
scripts.bitstring.Bits.endswith
def endswith(self, suffix, start=None, end=None)
Definition: bitstring.py:2711
scripts.bitstring.ByteAlignError
Definition: bitstring.py:117
scripts.bitstring.Bits.__getitem__
def __getitem__(self, key)
Definition: bitstring.py:889
scripts.bitstring.Bits._append
def _append(self, bs)
Definition: bitstring.py:2029
scripts.bitstring.BitArray.__copy__
def __copy__(self)
Definition: bitstring.py:3075
scripts.bitstring.Bits._assertsanity
def _assertsanity(self)
Definition: bitstring.py:1202
scripts.bitstring.Bits._findbytes
def _findbytes(self, bytes_, start, end, bytealigned)
Definition: bitstring.py:2359
scripts.bitstring.BitArray.__setitem__
def __setitem__(self, key, value)
Definition: bitstring.py:3086
scripts.bitstring.Bits.count
def count(self, value)
Definition: bitstring.py:2770
scripts.bitstring.BitArray
Definition: bitstring.py:2943
scripts.bitstring.ConstByteStore._appendstore
def _appendstore(self, store)
Definition: bitstring.py:174
scripts.bitstring.MmapByteArray.filelength
filelength
Definition: bitstring.py:406
scripts.bitstring.ConstBitStream.__add__
def __add__(self, bs)
Definition: bitstring.py:3838
scripts.bitstring.Bits.__xor__
def __xor__(self, bs)
Definition: bitstring.py:1127
scripts.bitstring.ConstBitStream.peeklist
def peeklist(self, fmt, **kwargs)
Definition: bitstring.py:3969
scripts.bitstring.BitArray.prepend
def prepend(self, bs)
Definition: bitstring.py:3434
scripts.bitstring.Bits._setuie
def _setuie(self, i)
Definition: bitstring.py:1724
scripts.bitstring.ConstByteStore.byteoffset
def byteoffset(self)
Definition: bitstring.py:212
scripts.bitstring.Bits._imul
def _imul(self, n)
Definition: bitstring.py:2204
scripts.bitstring.ConstByteStore.bitlength
bitlength
Definition: bitstring.py:147
scripts.bitstring.Bits._invert_all
def _invert_all(self)
Definition: bitstring.py:2183
scripts.bitstring.BitArray.__init__
def __init__(self, auto=None, length=None, offset=None, **kwargs)
Definition: bitstring.py:3019
scripts.bitstring.Bits.__ne__
def __ne__(self, bs)
Definition: bitstring.py:999
scripts.bitstring.Bits.__len__
def __len__(self)
Definition: bitstring.py:934
scripts.bitstring.ConstByteStore.__init__
def __init__(self, data, bitlength=None, offset=None)
Definition: bitstring.py:139
scripts.bitstring.ConstByteStore.getbyteslice
def getbyteslice(self, start, end)
Definition: bitstring.py:158
scripts.bitstring.Bits._readbytes
def _readbytes(self, length, start)
Definition: bitstring.py:1342
scripts.bitstring.Bits._readlist
def _readlist(self, fmt, pos, **kwargs)
Definition: bitstring.py:2282
scripts.bitstring.Bits.length
length
Definition: bitstring.py:2820
Belle2::slice
std::vector< Atom > slice(std::vector< Atom > vec, int s, int e)
Slice the vector to contain only elements with indexes s .. e (included)
Definition: Splitter.h:89
scripts.bitstring.Bits.bin
bin
Definition: bitstring.py:2829
scripts.bitstring.Bits.__nonzero__
def __nonzero__(self)
Definition: bitstring.py:1195
scripts.bitstring.pack
def pack(fmt, *values, **kwargs)
Definition: bitstring.py:4164
scripts.bitstring.BitArray.ror
def ror(self, bits, start=None, end=None)
Definition: bitstring.py:3516
scripts.bitstring.Bits._gethex
def _gethex(self)
Definition: bitstring.py:1941
scripts.bitstring.Bits.cut
def cut(self, bits, start=None, end=None, count=None)
Definition: bitstring.py:2547
scripts.bitstring.Bits.__and__
def __and__(self, bs)
Definition: bitstring.py:1075
scripts.bitstring.Bits._readbits
def _readbits(self, length, start)
Definition: bitstring.py:2243
scripts.bitstring.Bits._ixor
def _ixor(self, bs)
Definition: bitstring.py:2240
scripts.bitstring.tidy_input_string
def tidy_input_string(s)
Definition: bitstring.py:462
scripts.bitstring.Bits.__str__
def __str__(self)
Definition: bitstring.py:938
scripts.bitstring.BitArray.__iadd__
def __iadd__(self, bs)
Definition: bitstring.py:3066
scripts.bitstring.Bits._reverse
def _reverse(self)
Definition: bitstring.py:2037
scripts.bitstring.ConstByteStore._rawarray
_rawarray
Definition: bitstring.py:141
scripts.bitstring.Bits._getfloat
def _getfloat(self)
Definition: bitstring.py:1582
scripts.bitstring.Bits._iand
def _iand(self, bs)
Definition: bitstring.py:2237
scripts.bitstring.Bits._getintbe
def _getintbe(self)
Definition: bitstring.py:1486
scripts.bitstring.Bits.hex
hex
Definition: bitstring.py:2826
scripts.bitstring.Bits._readue
def _readue(self, pos)
Definition: bitstring.py:1647
scripts.bitstring.Bits.findall
def findall(self, bs, start=None, end=None, count=None, bytealigned=None)
Definition: bitstring.py:2456
scripts.bitstring.Bits._setue
def _setue(self, i)
Definition: bitstring.py:1625
scripts.bitstring.ConstBitStream._clear
def _clear(self)
Definition: bitstring.py:3824
scripts.bitstring.Bits._setbytes_safe
def _setbytes_safe(self, data, length=None, offset=0)
Definition: bitstring.py:1321
scripts.bitstring.Bits._setauto
def _setauto(self, s, length, offset)
Definition: bitstring.py:1252
scripts.bitstring.Bits._readintle
def _readintle(self, length, start)
Definition: bitstring.py:1535
scripts.bitstring.Bits._readfloat
def _readfloat(self, length, start)
Definition: bitstring.py:1564
scripts.bitstring.BitArray.__delitem__
def __delitem__(self, key)
Definition: bitstring.py:3194
scripts.bitstring.Bits
Definition: bitstring.py:684
scripts.bitstring.Bits._readuie
def _readuie(self, pos)
Definition: bitstring.py:1735
scripts.bitstring.Bits.tofile
def tofile(self, f)
Definition: bitstring.py:2662
scripts.bitstring.BitArray.__irshift__
def __irshift__(self, n)
Definition: bitstring.py:3258
scripts.bitstring.BitArray.clear
def clear(self)
Definition: bitstring.py:3620
scripts.bitstring.Bits._setbin_unsafe
def _setbin_unsafe(self, binstring)
Definition: bitstring.py:1837
scripts.bitstring.BitArray.append
def append(self, bs)
Definition: bitstring.py:3424
scripts.bitstring.ConstByteStore.bytelength
def bytelength(self)
Definition: bitstring.py:164
scripts.bitstring.ConstBitStream.pos
pos
Definition: bitstring.py:4003
scripts.bitstring.Bits.any
def any(self, value, pos=None)
Definition: bitstring.py:2748
scripts.bitstring.Bits.__add__
def __add__(self, bs)
Definition: bitstring.py:864
scripts.bitstring.ConstBitStream._setbitpos
def _setbitpos(self, pos)
Definition: bitstring.py:3812
scripts.bitstring.expand_brackets
def expand_brackets(s)
Definition: bitstring.py:645
scripts.bitstring.Bits._datastore
_datastore
Definition: bitstring.py:1250
scripts.bitstring.BitStream.__init__
def __init__(self, auto=None, length=None, offset=None, **kwargs)
Definition: bitstring.py:4092
scripts.bitstring.Bits._readint
def _readint(self, length, start)
Definition: bitstring.py:1440
scripts.bitstring.Error.params
params
Definition: bitstring.py:95
scripts.bitstring.Bits.len
len
Definition: bitstring.py:2817
scripts.bitstring.BitStream
Definition: bitstring.py:4014
scripts.bitstring.Bits.__mul__
def __mul__(self, n)
Definition: bitstring.py:1051
scripts.bitstring.BitArray.reverse
def reverse(self, start=None, end=None)
Definition: bitstring.py:3443
scripts.bitstring.Bits._setint
def _setint(self, int_, length=None)
Definition: bitstring.py:1417
scripts.bitstring.MmapByteArray.filemap
filemap
Definition: bitstring.py:413
scripts.bitstring.Bits._setuint
def _setuint(self, uint, length=None)
Definition: bitstring.py:1358
scripts.bitstring.Bits.__repr__
def __repr__(self)
Definition: bitstring.py:965
scripts.bitstring.Bits.rfind
def rfind(self, bs, start=None, end=None, bytealigned=None)
Definition: bitstring.py:2508
scripts.bitstring.MmapByteArray.bytelength
bytelength
Definition: bitstring.py:412
scripts.bitstring.Bits._readhex
def _readhex(self, length, start)
Definition: bitstring.py:1924
scripts.bitstring.Bits._truncateend
def _truncateend(self, bits)
Definition: bitstring.py:2062
scripts.bitstring.Bits._sethex
def _sethex(self, hexstring)
Definition: bitstring.py:1906