首页 > 解决方案 > 是否有推荐的模式来构建具有嵌套类型的 Flatbuffers?

问题描述

我有一个带有许多嵌套表的flatbuffers模式。Typescriptflatbuffers 中,我能够让每个表公开一个在创建时to_offset返回表的函数。WIPOffset然后我可以将结果分配给更高级别类型的嵌套字段,并且效果很好。

在 Rust flatbuffers 中,我无法完成这项工作,因为它需要多个可变借用,这当然是不允许的。

您有什么方法可以推荐使用像这样的嵌套模式,其中在整个模式中以更高级别的类型使用各种表?

这是我想做的一个粗略的例子:


table A {
  f1: string;
}
    
table B {
  fa: A;
  f2: uint;
}

table C {
  fa: A;
  f3: ushort;
}

fn build_a_offset<'a>(fbb: &'a mut FlatBufferBuilder) -> WIPOffset<A<'a>> {
  let args = AArgs {...
  };

  let a = A::create(fbb, &args);

  a
}

fn build_b_buf() -> Vec<u8> {
  let mut fbb = FlatBufferBuilder::new_with_capacity(1024);
  
  let a_offset = build_a_offset(&mut fbb);

  let b_args = BArgs {
    a: a_offset,
    f2: 30u32,
  }

  let b = B::create(&mut fbb, f_args);

  fbb.finish(b); 

  fbb.finished_data().to_vec()

}

关于如何正确构建它的任何建议都将非常有帮助。

标签: rustflatbuffers

解决方案


I did find an answer, I was not using lifetimes correctly.

fn build_a_offset<'a>(fbb: &'mut FlatBufferBuilder<'fbb>) -> WIPOffset<A<'a>> {
  let args = AArgs {...
  };

  let a = A::create(fbb, &args);

  a
}

fn build_b_buf() -> Vec<u8> {
  let mut fbb = FlatBufferBuilder::new_with_capacity(1024);
  
  let a_offset = build_a_offset(&mut fbb);

  let b_args = BArgs {
    a: a_offset,
    f2: 30u32,
  }

  let b = B::create(&mut fbb, f_args);

  fbb.finish(b); 

  fbb.finished_data().to_vec()

}

I needed to change the signature for the fbb ref to this:

fbb: &'mut FlatBufferBuilder<'fbb>

It was appending the suffix lifetime instead of the lifetime prepending the reference. This is because a prepended lifetime controls the life of the reference, and what is required is to control the life of the data included in the reference (that is what an appended <'fbb> does in Rust).

It would be good to add more examples to the tutorial for things like this. I could help at some point if that is something you need.


推荐阅读