Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions construct/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5245,6 +5245,10 @@ class Transformed(Subconstruct):
>>> d.parse(b"\x00\x00")
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
"""
converters = {bytes2bits: "bytes2bits",
bits2bytes: "bits2bytes",
swapbytes: "swapbytes",
swapbitsinbytes: "swapbitsinbytes"}

def __init__(self, subcon, decodefunc, decodeamount, encodefunc, encodeamount):
super().__init__(subcon)
Expand All @@ -5261,6 +5265,24 @@ def _parse(self, stream, context, path):
data = self.decodefunc(data)
return self.subcon._parsereport(io.BytesIO(data), context, path)

def _emitparse(self, code):
decodeamount = ""
if isinstance(self.decodeamount, int):
decodeamount = int(self.decodeamount)

aid = code.allocateId()
decFunc = self.converters[self.decodefunc]

code.append(f"""
from construct.lib.binary import bytes2bits, bits2bytes
from io import BytesIO
def Transforming_{aid}(ioOrig, this):
data = ioOrig.read({decodeamount})
io = BytesIO({decFunc}(data))
return {self.subcon._emitparse(code)}
""")
return f"Transforming_{aid}(io, this)"

def _build(self, obj, stream, context, path):
stream2 = io.BytesIO()
buildret = self.subcon._build(obj, stream2, context, path)
Expand All @@ -5272,6 +5294,21 @@ def _build(self, obj, stream, context, path):
stream_write(stream, data, len(data), path)
return buildret

def _emitbuild(self, code):
aid = code.allocateId()
encFunc = self.converters[self.encodefunc]

code.append(f"""
from construct.lib.binary import bytes2bits, bits2bytes
from io import BytesIO
def TransformingBuild_{aid}(obj, this, io_):
io = BytesIO()
{self.subcon._emitbuild(code)}
io_.write({encFunc}(io.getvalue()))
return obj
""")
return f"TransformingBuild_{aid}(obj, this, io)"

def _sizeof(self, context, path):
if self.decodeamount is None or self.encodeamount is None:
raise SizeofError(path=path)
Expand Down