Skip to content

Commit d09b0e3

Browse files
committed
Simplify bytes_strip_right and bytes_terminate implementations
Python has builtins that do almost exactly what these methods do.
1 parent b54805c commit d09b0e3

File tree

1 file changed

+9
-22
lines changed

1 file changed

+9
-22
lines changed

kaitaistruct.py

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -306,31 +306,14 @@ def ensure_fixed_contents(self, expected):
306306

307307
@staticmethod
308308
def bytes_strip_right(data, pad_byte):
309-
new_len = len(data)
310-
if PY2:
311-
# data[...] must yield an integer, to compare with integer pad_byte
312-
data = bytearray(data)
313-
314-
while new_len > 0 and data[new_len - 1] == pad_byte:
315-
new_len -= 1
316-
317-
return data[:new_len]
309+
return data.rstrip(KaitaiStream.byte_from_int(pad_byte))
318310

319311
@staticmethod
320312
def bytes_terminate(data, term, include_term):
321-
new_len = 0
322-
max_len = len(data)
323-
if PY2:
324-
# data[...] must yield an integer, to compare with integer term
325-
data = bytearray(data)
326-
327-
while new_len < max_len and data[new_len] != term:
328-
new_len += 1
329-
330-
if include_term and new_len < max_len:
331-
new_len += 1
332-
333-
return data[:new_len]
313+
new_data, term_byte, _ = data.partition(KaitaiStream.byte_from_int(term))
314+
if include_term:
315+
new_data += term_byte
316+
return new_data
334317

335318
# ========================================================================
336319
# Byte array processing
@@ -376,6 +359,10 @@ def int_from_byte(v):
376359
return ord(v)
377360
return v
378361

362+
@staticmethod
363+
def byte_from_int(i):
364+
return chr(i) if PY2 else bytes([i])
365+
379366
@staticmethod
380367
def byte_array_index(data, i):
381368
return KaitaiStream.int_from_byte(data[i])

0 commit comments

Comments
 (0)