Skip to content

Commit 07aea9c

Browse files
committed
Add bytes_terminate_multi() and read_bytes_term_multi()
See kaitai-io/kaitai_struct#187
1 parent 812ae7e commit 07aea9c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

kaitaistruct.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,31 @@ def read_bytes_term(self, term, include_term, consume_term, eos_error):
431431

432432
r += c
433433

434+
def read_bytes_term_multi(self, term, include_term, consume_term, eos_error):
435+
self.align_to_byte()
436+
unit_size = len(term)
437+
r = bytearray()
438+
while True:
439+
c = self._io.read(unit_size)
440+
if len(c) < unit_size:
441+
if eos_error:
442+
raise Exception(
443+
"end of stream reached, but no terminator %s found" %
444+
(repr(term),)
445+
)
446+
447+
r += c
448+
return bytes(r)
449+
450+
if c == term:
451+
if include_term:
452+
r += c
453+
if not consume_term:
454+
self._io.seek(-unit_size, SEEK_CUR)
455+
return bytes(r)
456+
457+
r += c
458+
434459
def ensure_fixed_contents(self, expected):
435460
actual = self._io.read(len(expected))
436461
if actual != expected:
@@ -451,6 +476,17 @@ def bytes_terminate(data, term, include_term):
451476
return data[:]
452477
return data[:term_index + (1 if include_term else 0)]
453478

479+
@staticmethod
480+
def bytes_terminate_multi(data, term, include_term):
481+
unit_size = len(term)
482+
search_idx = data.find(term)
483+
while True:
484+
if search_idx == -1:
485+
return data[:]
486+
if search_idx % unit_size == 0:
487+
return data[:search_idx + (unit_size if include_term else 0)]
488+
search_idx = data.find(term, search_idx + 1)
489+
454490
# endregion
455491

456492
# endregion

0 commit comments

Comments
 (0)