Number of bytes in python construct subcontext

31 views Asked by At

I am trying to build an Adapter for the Python Construct (2.10) library.

The goal is to write out a number as a zero-padded string. The file format I'm working with (NITFS) does this in lots of places, so a re-usable adapter would be ideal.

I have this:

import construct

class NPI(construct.Adapter):
    def __init__(self, subcon, length):
        construct.Adapter.__init__(self, subcon)
        self.length = length

    def _decode(self, obj, context, path):
        # TODO
        pass

    def _encode(self, obj, context, path):
        return str(obj).zfill(self.length).encode('ascii')

class NitfFile:
    def writeFile(self):
        rootStructure = construct.Struct(
            "FHDR" / construct.Const(b"NITF"),
            "CLEVEL" / NPI(construct.Byte[2], length=2)
        )
        bytes = rootStructure.build(dict(CLEVEL=3))

(Minimised - the actual format is obviously larger).

The part I'd like to avoid is specifying the length twice in the NPI(construct.Byte[2], length=2) field. Its always going to be the same.

Is there a way to get the number of bytes within my Adapter? Or is there a better pattern to address this kind of concern.

0

There are 0 answers