kaitai-io/kaitai_struct

Optimize generation if type does not depend on endianness

Mingun opened this issue · 0 comments

Currently, when endian is variable, complier always generate the two versions of code even if it will be the same (i.e. there are no fields that occupies more that 1 byte). For example, for this KSY:

meta:
  id: test_type
  endian:
    switch-on: 1
    cases:
      1: be
      2: le
seq:
  - id: seq
    size: 1
instances:
  instance:
    size: 1

... the following JS code are generated (on kaitai-io/kaitai_struct_compiler@4cd8d59):

function TestType(_io, _parent, _root) {
  this._io = _io;
  this._parent = _parent;
  this._root = _root || this;

  this._read();
}
TestType.prototype._read = function() {
  switch (1) {
  case 1:
    this._is_le = false;
    break;
  case 2:
    this._is_le = true;
    break;
  }

  if (this._is_le === true) {
    this._readLE();
  } else if (this._is_le === false) {
    this._readBE();
  } else {
    throw new KaitaiStream.UndecidedEndiannessError();
  }
}
TestType.prototype._readLE = function() {
  this.seq = this._io.readBytes(1);
}
TestType.prototype._readBE = function() {
  this.seq = this._io.readBytes(1);
}
Object.defineProperty(TestType.prototype, 'instance', {
  get: function() {
    if (this._m_instance !== undefined)
      return this._m_instance;
    if (this._is_le) {
      this._m_instance = this._io.readBytes(1);
    } else {
      this._m_instance = this._io.readBytes(1);
    }
    return this._m_instance;
  }
});

The compiler could track if particular type / parse instance actually depends on endiannes and generate only one variant of code if it doesn't.