0

所以我有这样的记录:

class Property < BinData::Record
    endian :little

    int32  :name_len
    string :name, read_length: :name_len

    # want to quit here.

    int32 :type_len
    string :type, read_length: :type_len
end

有没有办法让我在读取 :name_len 和 :name 后停止读取记录,只有当 :name 等于某个值时?或者,一旦您开始读取带有 Record 的文件,它就必须一直运行?

我知道我可以使用 :onlyif 跳过所有剩余的内容,但是有没有办法将 :onlyif 放在之后的所有内容上?您可以在选择上加上 :onlyif 吗?

我试过的代码:

class Property < BinData::Record
    endian :little

    int32  :name_len
    string :name, read_length: :name_len

    int32 :type_len, :onlyif => :not_none?
    string :type, read_length: :type_len, :onlyif => :not_none?

    int64 :data_len, :onlyif => :not_none?    
    choice :data, :onlyif => :not_none?, selection: :type do
        int32 "IntProperty\x00"

        float "FloatProperty\x00"

        struct "StrProperty\x00" do
            int32 :len
            string :data, read_length: :len
        end 

        struct "NameProperty\x00" do
            int32 :len
            string :data, read_length: :len
        end

        struct "ArrayProperty\x00" do
            int32 :num_items
            array :properties, type: :property, initial_length: :num_items
        end
    end

    def not_none?
        name != 'None\x00'
    end
end

我还尝试将 :name_len 和 :name 下面的所有内容放在它自己的记录中并这样做:

class Property < BinData::Record
    endian :little

    string_record :name

    property_data :p_data, :onlyif => :not_none?

    def not_none?
        name.data != 'None\x00'
    end 
end

但这不起作用,因为如果我将 PropertyData Record 放在上面(它必须是因为 Property 需要知道 PropertyData 是什么)然后它会出错,因为 PropertyData 需要知道 Property 是什么(因为它用该类型填充数组)。他们没有办法知道彼此的存在,因为他们都互相使用。

4

1 回答 1

0

[T]这不起作用,因为如果我将 PropertyData Record 放在上面(它必须是因为 Property 需要知道 PropertyData 是什么)然后它会出错,因为 PropertyData 需要知道 Property 是什么(因为它用那种)。

您可以通过在 Property 之前声明 PropertyData 类来解决此问题,但在之后填写:

class PropertyData < BinData::Record; end # Forward declaration

class Property < BinData::Record
  endian :little

  # ...
end

class PropertyData < BinData::Record
  endian :little

  # ...
end

list.rb您可以在示例中看到同样的事情发生。

于 2016-06-08T15:02:18.980 回答