使用Kaitai Struct解析操作码

时间:2016-07-21 20:08:12

标签: java bson hexdump preon kaitai-struct

在Kaitai Struct中完成我的第一步,我一直在努力做BSON解析器作为练习。解析BSON元素的我的.ksy代码现在看起来像这样:

  element:
    seq:
      - id: el_type
        type: u1
        enum: bson_type
      - id: el_name
        type: strz
        encoding: UTF-8
        if: el_type != bson_type::end_of_document
      - id: el_string
        type: bson_string
        if: el_type == bson_type::string
      - id: el_document
        type: bson_document
        if: el_type == bson_type::document
      - id: el_boolean
        type: u1
        if: el_type == bson_type::boolean
      - id: el_int32
        type: s4
        if: el_type == bson_type::int32
      - id: el_int64
        type: s4
        if: el_type == bson_type::int64
enums:
  bson_type:
    0: end_of_document
    1: double
    2: string
    3: document
    8: boolean
    0x10: int32
    0x12: int64

你可能已经注意到,有很多重复。每次想要做其他元素类型时,只需要复制if块。更糟糕的是,你基本上必须在每个这样的领域复制东西3次,即:

  - id: el_string                    # <= string!
    type: bson_string                # <= string!
    if: el_type == bson_type::string # <= string!

我的目标语言是Java。在Kaitai之前,我只尝试了Preon,并且我们有条款如:

@Choices(prefixSize = 8, alternatives = {
    @Choice(condition = "prefix==0x01", type = FloatNamedElement.class),
    @Choice(condition = "prefix==0x02", type = UTF8NamedElement.class)
}
private NamedElement elements;

您可以根据“前缀”的值自动获取这两个元素。是不是可以在开泰做到这一点?

1 个答案:

答案 0 :(得分:2)

嗯,你是对的,这个功能已经被要求了3到4次;)我filed an issue为此。

我无法就Preon的实施达成一致,但对我来说似乎非常有限。你只能有一个“前缀”,它总是整数,它总是必须紧跟你的选择点。

我想实现一个更通用的switch样式语句,类似于:

  - id: value
    switch: code
    cases:
      string:
        type: bson_string
      document:
        type: bson_document
      boolean:
        type: u1
      int32:
        type: s4
      int64:
        type: s8

你怎么看?

请注意,您可能无法获得“正确的”OOP对象层次结构,因为您正在使用Preon。这是因为Preon的类是手工制作的,你可以实际执行公共超类并从中继承FloatNamedElementUTF8NamedElement,但我想不出在当前KS模型中这样做的方法现在