Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/bitstring/bitstream.py: 41%

191 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-25 06:15 +0000

1from __future__ import annotations 

2 

3from bitstring.classes import BitArray, Bits, BitsType 

4from bitstring.utils import tokenparser 

5from bitstring.exceptions import ReadError, ByteAlignError, CreationError 

6from typing import Union, List, Any, Optional, overload, TypeVar, Tuple 

7import copy 

8import numbers 

9 

10TConstBitStream = TypeVar("TConstBitStream", bound='ConstBitStream') 

11 

12 

13class ConstBitStream(Bits): 

14 """A container or stream holding an immutable sequence of bits. 

15 

16 For a mutable container use the BitStream class instead. 

17 

18 Methods inherited from Bits: 

19 

20 all() -- Check if all specified bits are set to 1 or 0. 

21 any() -- Check if any of specified bits are set to 1 or 0. 

22 copy() -- Return a copy of the bitstring. 

23 count() -- Count the number of bits set to 1 or 0. 

24 cut() -- Create generator of constant sized chunks. 

25 endswith() -- Return whether the bitstring ends with a sub-string. 

26 find() -- Find a sub-bitstring in the current bitstring. 

27 findall() -- Find all occurrences of a sub-bitstring in the current bitstring. 

28 join() -- Join bitstrings together using current bitstring. 

29 pp() -- Pretty print the bitstring. 

30 rfind() -- Seek backwards to find a sub-bitstring. 

31 split() -- Create generator of chunks split by a delimiter. 

32 startswith() -- Return whether the bitstring starts with a sub-bitstring. 

33 tobitarray() -- Return bitstring as a bitarray from the bitarray package. 

34 tobytes() -- Return bitstring as bytes, padding if needed. 

35 tofile() -- Write bitstring to file, padding if needed. 

36 unpack() -- Interpret bits using format string. 

37 

38 Other methods: 

39 

40 bytealign() -- Align to next byte boundary. 

41 peek() -- Peek at and interpret next bits as a single item. 

42 peeklist() -- Peek at and interpret next bits as a list of items. 

43 read() -- Read and interpret next bits as a single item. 

44 readlist() -- Read and interpret next bits as a list of items. 

45 readto() -- Read up to and including next occurrence of a bitstring. 

46 

47 Special methods: 

48 

49 Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^. 

50 

51 Properties: 

52 

53 bin -- The bitstring as a binary string. 

54 hex -- The bitstring as a hexadecimal string. 

55 oct -- The bitstring as an octal string. 

56 bytes -- The bitstring as a bytes object. 

57 int -- Interpret as a two's complement signed integer. 

58 uint -- Interpret as a two's complement unsigned integer. 

59 float / floatbe -- Interpret as a big-endian floating point number. 

60 bool -- For single bit bitstrings, interpret as True or False. 

61 se -- Interpret as a signed exponential-Golomb code. 

62 ue -- Interpret as an unsigned exponential-Golomb code. 

63 sie -- Interpret as a signed interleaved exponential-Golomb code. 

64 uie -- Interpret as an unsigned interleaved exponential-Golomb code. 

65 floatle -- Interpret as a little-endian floating point number. 

66 floatne -- Interpret as a native-endian floating point number. 

67 bfloat / bfloatbe -- Interpret as a big-endian 16-bit bfloat type. 

68 bfloatle -- Interpret as a little-endian 16-bit bfloat type. 

69 bfloatne -- Interpret as a native-endian 16-bit bfloat type. 

70 intbe -- Interpret as a big-endian signed integer. 

71 intle -- Interpret as a little-endian signed integer. 

72 intne -- Interpret as a native-endian signed integer. 

73 uintbe -- Interpret as a big-endian unsigned integer. 

74 uintle -- Interpret as a little-endian unsigned integer. 

75 uintne -- Interpret as a native-endian unsigned integer. 

76 

77 len -- Length of the bitstring in bits. 

78 pos -- The current bit position in the bitstring. 

79 """ 

80 

81 __slots__ = ('_pos') 

82 

83 def __init__(self, __auto: Optional[Union[BitsType, int]] = None, length: Optional[int] = None, 

84 offset: Optional[int] = None, pos: int = 0, **kwargs) -> None: 

85 """Either specify an 'auto' initialiser: 

86 A string of comma separated tokens, an integer, a file object, 

87 a bytearray, a boolean iterable or another bitstring. 

88 

89 Or initialise via **kwargs with one (and only one) of: 

90 bin -- binary string representation, e.g. '0b001010'. 

91 hex -- hexadecimal string representation, e.g. '0x2ef' 

92 oct -- octal string representation, e.g. '0o777'. 

93 bytes -- raw data as a bytes object, for example read from a binary file. 

94 int -- a signed integer. 

95 uint -- an unsigned integer. 

96 float / floatbe -- a big-endian floating point number. 

97 bool -- a boolean (True or False). 

98 se -- a signed exponential-Golomb code. 

99 ue -- an unsigned exponential-Golomb code. 

100 sie -- a signed interleaved exponential-Golomb code. 

101 uie -- an unsigned interleaved exponential-Golomb code. 

102 floatle -- a little-endian floating point number. 

103 floatne -- a native-endian floating point number. 

104 bfloat / bfloatbe - a big-endian bfloat format 16-bit floating point number. 

105 bfloatle -- a little-endian bfloat format 16-bit floating point number. 

106 bfloatne -- a native-endian bfloat format 16-bit floating point number. 

107 intbe -- a signed big-endian whole byte integer. 

108 intle -- a signed little-endian whole byte integer. 

109 intne -- a signed native-endian whole byte integer. 

110 uintbe -- an unsigned big-endian whole byte integer. 

111 uintle -- an unsigned little-endian whole byte integer. 

112 uintne -- an unsigned native-endian whole byte integer. 

113 filename -- the path of a file which will be opened in binary read-only mode. 

114 

115 Other keyword arguments: 

116 length -- length of the bitstring in bits, if needed and appropriate. 

117 It must be supplied for all integer and float initialisers. 

118 offset -- bit offset to the data. These offset bits are 

119 ignored and this is mainly intended for use when 

120 initialising using 'bytes' or 'filename'. 

121 pos -- Initial bit position, defaults to 0. 

122 

123 """ 

124 if pos < 0: 

125 pos += len(self._bitstore) 

126 if pos < 0 or pos > len(self._bitstore): 

127 raise CreationError(f"Cannot set pos to {pos} when length is {len(self._bitstore)}.") 

128 self._pos = pos 

129 self._bitstore.immutable = True 

130 

131 def _setbytepos(self, bytepos: int) -> None: 

132 """Move to absolute byte-aligned position in stream.""" 

133 self._setbitpos(bytepos * 8) 

134 

135 def _getbytepos(self) -> int: 

136 """Return the current position in the stream in bytes. Must be byte aligned.""" 

137 if self._pos % 8: 

138 raise ByteAlignError("Not byte aligned when using bytepos property.") 

139 return self._pos // 8 

140 

141 def _setbitpos(self, pos: int) -> None: 

142 """Move to absolute position bit in bitstream.""" 

143 if pos < 0: 

144 raise ValueError("Bit position cannot be negative.") 

145 if pos > self.len: 

146 raise ValueError("Cannot seek past the end of the data.") 

147 self._pos = pos 

148 

149 def _getbitpos(self) -> int: 

150 """Return the current position in the stream in bits.""" 

151 return self._pos 

152 

153 def _clear(self) -> None: 

154 Bits._clear(self) 

155 self._pos = 0 

156 

157 def __copy__(self: TConstBitStream) -> TConstBitStream: 

158 """Return a new copy of the ConstBitStream for the copy module.""" 

159 # Note that if you want a new copy (different ID), use _copy instead. 

160 # The copy can use the same datastore as it's immutable. 

161 s = self.__class__() 

162 s._bitstore = self._bitstore 

163 # Reset the bit position, don't copy it. 

164 s._pos = 0 

165 return s 

166 

167 def __add__(self: TConstBitStream, bs: BitsType) -> TConstBitStream: 

168 """Concatenate bitstrings and return new bitstring. 

169 

170 bs -- the bitstring to append. 

171 

172 """ 

173 s = Bits.__add__(self, bs) 

174 s._pos = 0 

175 return s 

176 

177 def append(self, bs: BitsType) -> None: 

178 """Append a bitstring to the current bitstring. 

179 

180 bs -- The bitstring to append. 

181 

182 The current bit position will be moved to the end of the BitStream. 

183 

184 """ 

185 self._append(bs) 

186 self._pos = len(self) 

187 

188 def __repr__(self) -> str: 

189 """Return representation that could be used to recreate the bitstring. 

190 

191 If the returned string is too long it will be truncated. See __str__(). 

192 

193 """ 

194 return self._repr(self.__class__.__name__, len(self), self._bitstore.offset, self._bitstore.filename, self._pos) 

195 

196 def overwrite(self, bs: BitsType, pos: Optional[int] = None) -> None: 

197 """Overwrite with bs at bit position pos. 

198 

199 bs -- The bitstring to overwrite with. 

200 pos -- The bit position to begin overwriting from. 

201 

202 The current bit position will be moved to the end of the overwritten section. 

203 Raises ValueError if pos < 0 or pos > len(self). 

204 

205 """ 

206 bs = Bits._create_from_bitstype(bs) 

207 if not bs.len: 

208 return 

209 if pos is None: 

210 pos = self._pos 

211 if pos < 0: 

212 pos += self._getlength() 

213 if pos < 0 or pos > self.len: 

214 raise ValueError("Overwrite starts outside boundary of bitstring.") 

215 self._overwrite(bs, pos) 

216 self._pos = pos + bs.len 

217 

218 def find(self, bs: BitsType, start: Optional[int] = None, end: Optional[int] = None, 

219 bytealigned: Optional[bool] = None) -> Union[Tuple[int], Tuple[()]]: 

220 """Find first occurrence of substring bs. 

221 

222 Returns a single item tuple with the bit position if found, or an 

223 empty tuple if not found. The bit position (pos property) will 

224 also be set to the start of the substring if it is found. 

225 

226 bs -- The bitstring to find. 

227 start -- The bit position to start the search. Defaults to 0. 

228 end -- The bit position one past the last bit to search. 

229 Defaults to len(self). 

230 bytealigned -- If True the bitstring will only be 

231 found on byte boundaries. 

232 

233 Raises ValueError if bs is empty, if start < 0, if end > len(self) or 

234 if end < start. 

235 

236 >>> BitStream('0xc3e').find('0b1111') 

237 (6,) 

238 

239 """ 

240 

241 p = super().find(bs, start, end, bytealigned) 

242 if p: 

243 self._pos = p[0] 

244 return p 

245 

246 def rfind(self, bs: BitsType, start: Optional[int] = None, end: Optional[int] = None, 

247 bytealigned: Optional[bool] = None) -> Union[Tuple[int], Tuple[()]]: 

248 """Find final occurrence of substring bs. 

249 

250 Returns a single item tuple with the bit position if found, or an 

251 empty tuple if not found. The bit position (pos property) will 

252 also be set to the start of the substring if it is found. 

253 

254 bs -- The bitstring to find. 

255 start -- The bit position to end the reverse search. Defaults to 0. 

256 end -- The bit position one past the first bit to reverse search. 

257 Defaults to len(self). 

258 bytealigned -- If True the bitstring will only be found on byte 

259 boundaries. 

260 

261 Raises ValueError if bs is empty, if start < 0, if end > len(self) or 

262 if end < start. 

263 

264 """ 

265 p = super().rfind(bs, start, end, bytealigned) 

266 if p: 

267 self._pos = p[0] 

268 return p 

269 

270 @overload 

271 def read(self, fmt: int) -> Bits: 

272 ... 

273 

274 @overload 

275 def read(self, fmt: str) -> Any: 

276 ... 

277 

278 def read(self, fmt: Union[int, str]) -> Union[int, float, str, Bits, bool, bytes, None]: 

279 """Interpret next bits according to the format string and return result. 

280 

281 fmt -- Token string describing how to interpret the next bits. 

282 

283 Token examples: 'int:12' : 12 bits as a signed integer 

284 'uint:8' : 8 bits as an unsigned integer 

285 'float:64' : 8 bytes as a big-endian float 

286 'intbe:16' : 2 bytes as a big-endian signed integer 

287 'uintbe:16' : 2 bytes as a big-endian unsigned integer 

288 'intle:32' : 4 bytes as a little-endian signed integer 

289 'uintle:32' : 4 bytes as a little-endian unsigned integer 

290 'floatle:64': 8 bytes as a little-endian float 

291 'intne:24' : 3 bytes as a native-endian signed integer 

292 'uintne:24' : 3 bytes as a native-endian unsigned integer 

293 'floatne:32': 4 bytes as a native-endian float 

294 'hex:80' : 80 bits as a hex string 

295 'oct:9' : 9 bits as an octal string 

296 'bin:1' : single bit binary string 

297 'ue' : next bits as unsigned exp-Golomb code 

298 'se' : next bits as signed exp-Golomb code 

299 'uie' : next bits as unsigned interleaved exp-Golomb code 

300 'sie' : next bits as signed interleaved exp-Golomb code 

301 'bits:5' : 5 bits as a bitstring 

302 'bytes:10' : 10 bytes as a bytes object 

303 'bool' : 1 bit as a bool 

304 'pad:3' : 3 bits of padding to ignore - returns None 

305 

306 fmt may also be an integer, which will be treated like the 'bits' token. 

307 

308 The position in the bitstring is advanced to after the read items. 

309 

310 Raises ReadError if not enough bits are available. 

311 Raises ValueError if the format is not understood. 

312 

313 """ 

314 if isinstance(fmt, numbers.Integral): 

315 if fmt < 0: 

316 raise ValueError("Cannot read negative amount.") 

317 if fmt > self.len - self._pos: 

318 raise ReadError(f"Cannot read {fmt} bits, only {self.len - self._pos} available.") 

319 bs = self._slice(self._pos, self._pos + fmt) 

320 self._pos += fmt 

321 return bs 

322 p = self._pos 

323 _, token = tokenparser(fmt) 

324 if len(token) != 1: 

325 self._pos = p 

326 raise ValueError(f"Format string should be a single token, not {len(token)} " 

327 "tokens - use readlist() instead.") 

328 name, length, _ = token[0] 

329 if length is None: 

330 length = self.len - self._pos 

331 value, self._pos = self._readtoken(name, self._pos, length) 

332 return value 

333 

334 def readlist(self, fmt: Union[str, List[Union[int, str]]], **kwargs) \ 

335 -> List[Union[int, float, str, Bits, bool, bytes, None]]: 

336 """Interpret next bits according to format string(s) and return list. 

337 

338 fmt -- A single string or list of strings with comma separated tokens 

339 describing how to interpret the next bits in the bitstring. Items 

340 can also be integers, for reading new bitstring of the given length. 

341 kwargs -- A dictionary or keyword-value pairs - the keywords used in the 

342 format string will be replaced with their given value. 

343 

344 The position in the bitstring is advanced to after the read items. 

345 

346 Raises ReadError is not enough bits are available. 

347 Raises ValueError if the format is not understood. 

348 

349 See the docstring for 'read' for token examples. 'pad' tokens are skipped 

350 and not added to the returned list. 

351 

352 >>> h, b1, b2 = s.readlist('hex:20, bin:5, bin:3') 

353 >>> i, bs1, bs2 = s.readlist(['uint:12', 10, 10]) 

354 

355 """ 

356 value, self._pos = self._readlist(fmt, self._pos, **kwargs) 

357 return value 

358 

359 def readto(self: TConstBitStream, bs: BitsType, bytealigned: Optional[bool] = None) -> TConstBitStream: 

360 """Read up to and including next occurrence of bs and return result. 

361 

362 bs -- The bitstring to find. An integer is not permitted. 

363 bytealigned -- If True the bitstring will only be 

364 found on byte boundaries. 

365 

366 Raises ValueError if bs is empty. 

367 Raises ReadError if bs is not found. 

368 

369 """ 

370 if isinstance(bs, numbers.Integral): 

371 raise ValueError("Integers cannot be searched for") 

372 bs = Bits._create_from_bitstype(bs) 

373 oldpos = self._pos 

374 p = self.find(bs, self._pos, bytealigned=bytealigned) 

375 if not p: 

376 raise ReadError("Substring not found") 

377 self._pos += bs.len 

378 return self._slice(oldpos, self._pos) 

379 

380 @overload 

381 def peek(self: TConstBitStream, fmt: int) -> TConstBitStream: 

382 ... 

383 

384 @overload 

385 def peek(self, fmt: str) -> Union[int, float, str, TConstBitStream, bool, bytes, None]: 

386 ... 

387 

388 def peek(self: TConstBitStream, fmt: Union[int, str]) -> Union[int, float, str, TConstBitStream, bool, bytes, None]: 

389 """Interpret next bits according to format string and return result. 

390 

391 fmt -- Token string describing how to interpret the next bits. 

392 

393 The position in the bitstring is not changed. If not enough bits are 

394 available then all bits to the end of the bitstring will be used. 

395 

396 Raises ReadError if not enough bits are available. 

397 Raises ValueError if the format is not understood. 

398 

399 See the docstring for 'read' for token examples. 

400 

401 """ 

402 pos_before = self._pos 

403 value = self.read(fmt) 

404 self._pos = pos_before 

405 return value 

406 

407 def peeklist(self, fmt: Union[str, List[Union[int, str]]], **kwargs) \ 

408 -> List[Union[int, float, str, Bits, None]]: 

409 """Interpret next bits according to format string(s) and return list. 

410 

411 fmt -- One or more integers or strings with comma separated tokens describing 

412 how to interpret the next bits in the bitstring. 

413 kwargs -- A dictionary or keyword-value pairs - the keywords used in the 

414 format string will be replaced with their given value. 

415 

416 The position in the bitstring is not changed. If not enough bits are 

417 available then all bits to the end of the bitstring will be used. 

418 

419 Raises ReadError if not enough bits are available. 

420 Raises ValueError if the format is not understood. 

421 

422 See the docstring for 'read' for token examples. 

423 

424 """ 

425 pos = self._pos 

426 return_values = self.readlist(fmt, **kwargs) 

427 self._pos = pos 

428 return return_values 

429 

430 def bytealign(self) -> int: 

431 """Align to next byte and return number of skipped bits. 

432 

433 Raises ValueError if the end of the bitstring is reached before 

434 aligning to the next byte. 

435 

436 """ 

437 skipped = (8 - (self._pos % 8)) % 8 

438 self.pos += skipped 

439 return skipped 

440 

441 pos = property(_getbitpos, _setbitpos, 

442 doc="""The position in the bitstring in bits. Read and write. 

443 """) 

444 bitpos = property(_getbitpos, _setbitpos, 

445 doc="""The position in the bitstring in bits. Read and write. 

446 """) 

447 bytepos = property(_getbytepos, _setbytepos, 

448 doc="""The position in the bitstring in bytes. Read and write. 

449 """) 

450 

451 

452class BitStream(ConstBitStream, BitArray): 

453 """A container or stream holding a mutable sequence of bits 

454 

455 Subclass of the ConstBitStream and BitArray classes. Inherits all of 

456 their methods. 

457 

458 Methods: 

459 

460 all() -- Check if all specified bits are set to 1 or 0. 

461 any() -- Check if any of specified bits are set to 1 or 0. 

462 append() -- Append a bitstring. 

463 bytealign() -- Align to next byte boundary. 

464 byteswap() -- Change byte endianness in-place. 

465 clear() -- Remove all bits from the bitstring. 

466 copy() -- Return a copy of the bitstring. 

467 count() -- Count the number of bits set to 1 or 0. 

468 cut() -- Create generator of constant sized chunks. 

469 endswith() -- Return whether the bitstring ends with a sub-string. 

470 find() -- Find a sub-bitstring in the current bitstring. 

471 findall() -- Find all occurrences of a sub-bitstring in the current bitstring. 

472 insert() -- Insert a bitstring. 

473 invert() -- Flip bit(s) between one and zero. 

474 join() -- Join bitstrings together using current bitstring. 

475 overwrite() -- Overwrite a section with a new bitstring. 

476 peek() -- Peek at and interpret next bits as a single item. 

477 peeklist() -- Peek at and interpret next bits as a list of items. 

478 pp() -- Pretty print the bitstring. 

479 prepend() -- Prepend a bitstring. 

480 read() -- Read and interpret next bits as a single item. 

481 readlist() -- Read and interpret next bits as a list of items. 

482 readto() -- Read up to and including next occurrence of a bitstring. 

483 replace() -- Replace occurrences of one bitstring with another. 

484 reverse() -- Reverse bits in-place. 

485 rfind() -- Seek backwards to find a sub-bitstring. 

486 rol() -- Rotate bits to the left. 

487 ror() -- Rotate bits to the right. 

488 set() -- Set bit(s) to 1 or 0. 

489 split() -- Create generator of chunks split by a delimiter. 

490 startswith() -- Return whether the bitstring starts with a sub-bitstring. 

491 tobitarray() -- Return bitstring as a bitarray from the bitarray package. 

492 tobytes() -- Return bitstring as bytes, padding if needed. 

493 tofile() -- Write bitstring to file, padding if needed. 

494 unpack() -- Interpret bits using format string. 

495 

496 Special methods: 

497 

498 Mutating operators are available: [], <<=, >>=, +=, *=, &=, |= and ^= 

499 in addition to [], ==, !=, +, *, ~, <<, >>, &, | and ^. 

500 

501 Properties: 

502 

503 bin -- The bitstring as a binary string. 

504 hex -- The bitstring as a hexadecimal string. 

505 oct -- The bitstring as an octal string. 

506 bytes -- The bitstring as a bytes object. 

507 int -- Interpret as a two's complement signed integer. 

508 uint -- Interpret as a two's complement unsigned integer. 

509 float / floatbe -- Interpret as a big-endian floating point number. 

510 bool -- For single bit bitstrings, interpret as True or False. 

511 se -- Interpret as a signed exponential-Golomb code. 

512 ue -- Interpret as an unsigned exponential-Golomb code. 

513 sie -- Interpret as a signed interleaved exponential-Golomb code. 

514 uie -- Interpret as an unsigned interleaved exponential-Golomb code. 

515 floatle -- Interpret as a little-endian floating point number. 

516 floatne -- Interpret as a native-endian floating point number. 

517 bfloat / bfloatbe -- Interpret as a big-endian 16-bit bfloat type. 

518 bfloatle -- Interpret as a little-endian 16-bit bfloat type. 

519 bfloatne -- Interpret as a native-endian 16-bit bfloat type. 

520 intbe -- Interpret as a big-endian signed integer. 

521 intle -- Interpret as a little-endian signed integer. 

522 intne -- Interpret as a native-endian signed integer. 

523 uintbe -- Interpret as a big-endian unsigned integer. 

524 uintle -- Interpret as a little-endian unsigned integer. 

525 uintne -- Interpret as a native-endian unsigned integer. 

526 

527 len -- Length of the bitstring in bits. 

528 pos -- The current bit position in the bitstring. 

529 """ 

530 

531 __slots__ = () 

532 

533 def __init__(self, __auto: Optional[Union[BitsType, int]] = None, length: Optional[int] = None, 

534 offset: Optional[int] = None, pos: int = 0, **kwargs) -> None: 

535 """Either specify an 'auto' initialiser: 

536 A string of comma separated tokens, an integer, a file object, 

537 a bytearray, a boolean iterable or another bitstring. 

538 

539 Or initialise via **kwargs with one (and only one) of: 

540 bin -- binary string representation, e.g. '0b001010'. 

541 hex -- hexadecimal string representation, e.g. '0x2ef' 

542 oct -- octal string representation, e.g. '0o777'. 

543 bytes -- raw data as a bytes object, for example read from a binary file. 

544 int -- a signed integer. 

545 uint -- an unsigned integer. 

546 float / floatbe -- a big-endian floating point number. 

547 bool -- a boolean (True or False). 

548 se -- a signed exponential-Golomb code. 

549 ue -- an unsigned exponential-Golomb code. 

550 sie -- a signed interleaved exponential-Golomb code. 

551 uie -- an unsigned interleaved exponential-Golomb code. 

552 floatle -- a little-endian floating point number. 

553 floatne -- a native-endian floating point number. 

554 bfloat / bfloatbe - a big-endian bfloat format 16-bit floating point number. 

555 bfloatle -- a little-endian bfloat format 16-bit floating point number. 

556 bfloatne -- a native-endian bfloat format 16-bit floating point number. 

557 intbe -- a signed big-endian whole byte integer. 

558 intle -- a signed little-endian whole byte integer. 

559 intne -- a signed native-endian whole byte integer. 

560 uintbe -- an unsigned big-endian whole byte integer. 

561 uintle -- an unsigned little-endian whole byte integer. 

562 uintne -- an unsigned native-endian whole byte integer. 

563 filename -- the path of a file which will be opened in binary read-only mode. 

564 

565 Other keyword arguments: 

566 length -- length of the bitstring in bits, if needed and appropriate. 

567 It must be supplied for all integer and float initialisers. 

568 offset -- bit offset to the data. These offset bits are 

569 ignored and this is intended for use when 

570 initialising using 'bytes' or 'filename'. 

571 pos -- Initial bit position, defaults to 0. 

572 

573 """ 

574 ConstBitStream.__init__(self, __auto, length, offset, pos, **kwargs) 

575 if self._bitstore.immutable: 

576 self._bitstore = self._bitstore.copy() 

577 self._bitstore.immutable = False 

578 

579 def __copy__(self) -> BitStream: 

580 """Return a new copy of the BitStream.""" 

581 s_copy = BitStream() 

582 s_copy._pos = 0 

583 s_copy._bitstore = self._bitstore.copy() 

584 return s_copy 

585 

586 def __iadd__(self, bs: BitsType) -> BitStream: 

587 """Append bs to current bitstring. Return self. 

588 

589 bs -- the bitstring to append. 

590 

591 The current bit position will be moved to the end of the BitStream. 

592 """ 

593 self._append(bs) 

594 self._pos = len(self) 

595 return self 

596 

597 def prepend(self, bs: BitsType) -> None: 

598 """Prepend a bitstring to the current bitstring. 

599 

600 bs -- The bitstring to prepend. 

601 

602 """ 

603 bs = Bits._create_from_bitstype(bs) 

604 super().prepend(bs) 

605 self._pos = 0 

606 

607 def __setitem__(self, key: Union[slice, int], value: BitsType) -> None: 

608 length_before = len(self) 

609 super().__setitem__(key, value) 

610 if len(self) != length_before: 

611 self._pos = 0 

612 return 

613 

614 def __delitem__(self, key: Union[slice, int]) -> None: 

615 """Delete item or range. 

616 

617 >>> a = BitStream('0x001122') 

618 >>> del a[8:16] 

619 >>> print a 

620 0x0022 

621 

622 """ 

623 length_before = len(self) 

624 self._bitstore.__delitem__(key) 

625 if len(self) != length_before: 

626 self._pos = 0 

627 

628 def insert(self, bs: BitsType, pos: Optional[int] = None) -> None: 

629 """Insert bs at bit position pos. 

630 

631 bs -- The bitstring to insert. 

632 pos -- The bit position to insert at. 

633 

634 The current bit position will be moved to the end of the inserted section. 

635 Raises ValueError if pos < 0 or pos > len(self). 

636 

637 """ 

638 bs = Bits._create_from_bitstype(bs) 

639 if len(bs) == 0: 

640 return 

641 if bs is self: 

642 bs = self._copy() 

643 if pos is None: 

644 pos = self._pos 

645 if pos < 0: 

646 pos += self._getlength() 

647 if not 0 <= pos <= self._getlength(): 

648 raise ValueError("Invalid insert position.") 

649 self._insert(bs, pos) 

650 self._pos = pos + len(bs) 

651 

652 def replace(self, old: BitsType, new: BitsType, start: Optional[int] = None, end: Optional[int] = None, 

653 count: Optional[int] = None, bytealigned: Optional[bool] = None) -> int: 

654 """Replace all occurrences of old with new in place. 

655 

656 Returns number of replacements made. 

657 

658 old -- The bitstring to replace. 

659 new -- The replacement bitstring. 

660 start -- Any occurrences that start before this will not be replaced. 

661 Defaults to 0. 

662 end -- Any occurrences that finish after this will not be replaced. 

663 Defaults to len(self). 

664 count -- The maximum number of replacements to make. Defaults to 

665 replace all occurrences. 

666 bytealigned -- If True replacements will only be made on byte 

667 boundaries. 

668 

669 Raises ValueError if old is empty or if start or end are 

670 out of range. 

671 

672 """ 

673 if count == 0: 

674 return 0 

675 old = Bits._create_from_bitstype(old) 

676 new = Bits._create_from_bitstype(new) 

677 if not old.len: 

678 raise ValueError("Empty bitstring cannot be replaced.") 

679 start, end = self._validate_slice(start, end) 

680 if new is self: 

681 # Prevent self assignment woes 

682 new = copy.copy(self) 

683 length_before = len(self) 

684 replacement_count = self._replace(old, new, start, end, 0 if count is None else count, bytealigned) 

685 if len(self) != length_before: 

686 self._pos = 0 

687 return replacement_count