【问题标题】:Parsing opcodes with Kaitai Struct使用 Kaitai Struct 解析操作码
【发布时间】:2016-07-21 20:08:12
【问题描述】:

在 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;

您会根据“前缀”的值自动获取这两个元素。开泰可以吗?

【问题讨论】:

    标签: java bson hexdump preon kaitai-struct


    【解决方案1】:

    嗯,你是对的,这个功能已经被请求了 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 模型中这样做的方法。

    【讨论】:

    • 有趣的是,Preon 的一切都是有限的,除非你正在考虑它默认发货的编解码器。可扩展性实际上是创建 Preon 的关键原因之一,因为现有的框架都没有足够的可扩展性来适应我们遇到的所有用例。无论您要解决什么问题,我都坚信您可以通过添加 CodecCodecFactory 以及一些注释来扩展 Preon。
    • 您好,@WilfredSpringer,很高兴认识您!据我了解,在 Preon 中编写自己的 Codec 和类似的类在技术上将其从“声明性”领域转移到“命令性”领域,因为您实际上是编写手动读取/写入流的代码。这是我在这里唯一的一点,称 Preon 为“有限的”。如果冒犯了你,我很抱歉,没有冒犯的意思。同时,自从提出这个问题以来已经过去了很长时间,Kaitai Struct 开箱即用地实现了类型切换。
    • 别担心,没有任何冒犯。 ;-) 我猜 Preon 允许你扩展它的声明能力。通过实现单个界面创建新版本的 Preon,允许未来用户仅以声明方式利用该新功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多