Skip to content

Commit 68cb21d

Browse files
committed
write_bytes_limit(): small improvements
1 parent 67ffcff commit 68cb21d

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

kaitaistruct.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -739,14 +739,25 @@ def _write_bytes_not_aligned(self, buf):
739739

740740
def write_bytes_limit(self, buf, size, term, pad_byte):
741741
n = len(buf)
742+
# Strictly speaking, this assertion is redundant because it is already
743+
# done in the corresponding _check() method in the generated code, but
744+
# it seems to make sense to include it here anyway so that this method
745+
# itself does something reasonable for every set of arguments.
746+
#
747+
# However, it should never be `false` when operated correctly (and in
748+
# this case, assigning inconsistent values to fields of a KS-generated
749+
# object is considered correct operation if the user application calls
750+
# the corresponding _check(), which we know would raise an error and
751+
# thus the code should not reach _write() and this method at all). So
752+
# it's by design that this throws AssertionError, not any specific
753+
# error, because it's not intended to be caught in user applications,
754+
# but avoided by calling all _check() methods correctly.
755+
assert n <= size, "writing %d bytes, but %d bytes were given" % (size, n)
756+
742757
self.write_bytes(buf)
743758
if n < size:
744759
self.write_u1(term)
745-
pad_len = size - n - 1
746-
for _ in range(pad_len):
747-
self.write_u1(pad_byte)
748-
elif n > size:
749-
raise ValueError("writing %d bytes, but %d bytes were given" % (size, n))
760+
self.write_bytes(KaitaiStream.byte_from_int(pad_byte) * (size - n - 1))
750761

751762
# endregion
752763

0 commit comments

Comments
 (0)