Skip to content

Commit 9d85560

Browse files
authored
Merge pull request #42 from dgelessus/simplify_terminate_strip_right
Simplify bytes_strip_right and bytes_terminate implementations
2 parents 4b97420 + 69e68a7 commit 9d85560

File tree

1 file changed

+9
-22
lines changed

1 file changed

+9
-22
lines changed

kaitaistruct.py

+9-22
Original file line numberDiff line numberDiff line change
@@ -328,31 +328,14 @@ def ensure_fixed_contents(self, expected):
328328

329329
@staticmethod
330330
def bytes_strip_right(data, pad_byte):
331-
new_len = len(data)
332-
if PY2:
333-
# data[...] must yield an integer, to compare with integer pad_byte
334-
data = bytearray(data)
335-
336-
while new_len > 0 and data[new_len - 1] == pad_byte:
337-
new_len -= 1
338-
339-
return data[:new_len]
331+
return data.rstrip(KaitaiStream.byte_from_int(pad_byte))
340332

341333
@staticmethod
342334
def bytes_terminate(data, term, include_term):
343-
new_len = 0
344-
max_len = len(data)
345-
if PY2:
346-
# data[...] must yield an integer, to compare with integer term
347-
data = bytearray(data)
348-
349-
while new_len < max_len and data[new_len] != term:
350-
new_len += 1
351-
352-
if include_term and new_len < max_len:
353-
new_len += 1
354-
355-
return data[:new_len]
335+
new_data, term_byte, _ = data.partition(KaitaiStream.byte_from_int(term))
336+
if include_term:
337+
new_data += term_byte
338+
return new_data
356339

357340
# ========================================================================
358341
# Byte array processing
@@ -398,6 +381,10 @@ def int_from_byte(v):
398381
return ord(v)
399382
return v
400383

384+
@staticmethod
385+
def byte_from_int(i):
386+
return chr(i) if PY2 else bytes([i])
387+
401388
@staticmethod
402389
def byte_array_index(data, i):
403390
return KaitaiStream.int_from_byte(data[i])

0 commit comments

Comments
 (0)