Skip to content

Commit

Permalink
Refactored _write function, added tests for bytes written
Browse files Browse the repository at this point in the history
  • Loading branch information
joost-j committed Feb 16, 2024
1 parent 9ed88d6 commit 07b8c18
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
2 changes: 1 addition & 1 deletion dissect/cstruct/cstruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from dissect.cstruct.expression import Expression
from dissect.cstruct.parser import CStyleParser, TokenParser
from dissect.cstruct.types import (
LEB128,
Array,
ArrayMetaType,
BaseType,
Expand All @@ -29,7 +30,6 @@
Wchar,
WcharArray,
)
from dissect.cstruct.types.leb128 import LEB128


class cstruct:
Expand Down
8 changes: 5 additions & 3 deletions dissect/cstruct/types/leb128.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def _read_0(cls, stream: BinaryIO, context: dict[str, Any] = None) -> LEB128:
return result

@classmethod
def _write(cls, stream: BinaryIO, data: int) -> LEB128:
def _write(cls, stream: BinaryIO, data: int) -> int:
# only write negative numbers when in signed mode
if data < 0 and not cls.signed:
raise ValueError("Attempt to encode a negative integer using unsigned LEB128 encoding")
Expand All @@ -64,8 +64,10 @@ def _write(cls, stream: BinaryIO, data: int) -> LEB128:
not cls.signed and data == 0
):
result.append(byte)
stream.write(result)
return len(result)
break

# Set high-order bit of byte
result.append(0x80 | byte)

stream.write(result)
return len(result)
16 changes: 16 additions & 0 deletions tests/test_types_leb128.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import io

import pytest

from dissect.cstruct.cstruct import cstruct
Expand Down Expand Up @@ -159,3 +161,17 @@ def test_leb128_write_negatives(cs: cstruct):
with pytest.raises(ValueError, match="Attempt to encode a negative integer using unsigned LEB128 encoding"):
cs.uleb128(-2).dumps()
assert cs.ileb128(-2).dumps() == b"\x7e"


def test_leb128_unsigned_write_amount_written(cs: cstruct):
out1 = io.BytesIO()
bytes_written1 = cs.uleb128(2).write(out1)
assert bytes_written1 == out1.tell()

out2 = io.BytesIO()
bytes_written2 = cs.uleb128(4747).write(out2)
assert bytes_written2 == out2.tell()

out3 = io.BytesIO()
bytes_written3 = cs.uleb128(13371337).write(out3)
assert bytes_written3 == out3.tell()

0 comments on commit 07b8c18

Please sign in to comment.