How to calculate size of a field dynamically in Kaitai Struct?

I have to parse a stream of messages with known total size. There are some known fields in there and a chunk of bytes somewhere in between.

seq:
  - id: messages
    type: message
    repeat: eos

types:
  message:
    seq:
      - id: magic
        contents: [0xDC, 0x5A, 0x5C]
        size: 3
        
      - id: length
        type: u1

      - id: voltage_raw
        type: u2be
        
      - id: temperature
        type: s2be
        
      - id: current_1
        type: u4be
        
      - id: current_2
        type: u4be
        
      - id: chunk
        size: length - magic.size - 1 - 2 - 2 - 4 - 4
      # size of this chunk = length - (before.length) - (after.length)
      # don't want to calculate size manually
      # don't want to update it each time I decode new field from chunk
      # and place it before or after chunk
        
      - id: crc32
        type: u4
        if: length > 38

I would like size of the chunk to be calculated automatically based on size of data before/after with total length of the message. Obviously, all of the data to perform such operation is known at least at runtime.

Basically, I would like this chunk to shrink and expand dynamically based on message structure and total length.

Is there a way to achieve such behaviour?

Upvotes: 0

Views: 49

Answers (0)

Related Questions