kaitai-io / kaitai_struct

Kaitai Struct: declarative language to generate binary data parsers in C++ / C# / Go / Java / JavaScript / Lua / Nim / Perl / PHP / Python / Ruby
https://kaitai.io
4.04k stars 199 forks source link

Question: How remove zero values from the array? #998

Closed HenryOfCarim closed 1 year ago

HenryOfCarim commented 2 years ago

In my header block_offsets gets positions for other data chunks but some of the values are equal to zero and need to be removed from the array

  - {id: id_magic, type: u4}
  - {id: version, type: u2}
  - {id: num_blocks, type: u2}
  - {id: block_offsets, type: u4, repeat: expr, repeat-expr: num_blocks}

In python, it would look like this but I have no clue how to implement it in kaitai despite I tried.

valid_offsets = [block_offset for block offset in block_offsets if block_offset ]

KOLANICH commented 2 years ago

I guess you should evaluate if you really have to remove zero values. You cannot remove them but you can map an array to another array, each element of which can contain some elements of the original array. But it would be no better than just checking for each element if it is zero or not, if you use the array once.

HenryOfCarim commented 1 year ago

Okay, I finally found a solution

seq:
  - {id: id_magic, contents: [0x4c, 0x4d, 0x54, 0x00]}
  - {id: version, type: u2}
  - {id: num_blocks, type: u2}
  - {id: block_offsets, type: block_offset, repeat: expr, repeat-expr: num_blocks}

types:
  block_offset:
    seq:
      - {id: ofc_block, type: u4}
    instances:
      is_used:
        value: ofc_block != 0
      body:
          pos: ofc_block
          type: block_header
          if: is_used