flatbuffers icon indicating copy to clipboard operation
flatbuffers copied to clipboard

Rust: Builder should only be able to finish messages created by itself at compile time.

Open youyuanwu opened this issue 3 months ago • 1 comments

The following code should not compile in the first place:

table HelloRequest {
    name:string;
}

Using 2 builders to create 2 messages, and use 1 builder to finish the message created by another builder.

        let mut builder1 = FlatBufferBuilder::new();
        let bar_str1 = builder1.create_string("hello world0");
        let req1 = HelloRequest::create(
            &mut builder1,
            &HelloRequestArgs {
                name: Some(bar_str1),
            },
        );

        let mut builder2 = FlatBufferBuilder::new();
        let bar_str2 = builder2.create_string("hello3");
        let req2 = HelloRequest::create(
            &mut builder2,
            &HelloRequestArgs {
                name: Some(bar_str2),
            },
        );
        builder1.finish_minimal(req2);
        let req_x1 = flatbuffers::root::<HelloRequest>(&builder1.finished_data()).unwrap();
        assert_eq!(req_x1.name(), Some("hello3"));

The code fails at runtime expectedly:

led `Result::unwrap()` on an `Err` value: Unaligned { position: 26, unaligned_type: "u32", error_trace: ErrorTrace([TableField { field_name: "name", position: 26 }]) }

Ideally this code snippet should not compile in the first place, that the programming error should be detected at compile time instead of runtime. If there is a chance that there is no runtime error, we have corrupted data. Maybe the finish_minimal api on the builder should be marked as unsafe and indicate to user.

youyuanwu avatar Sep 14 '25 17:09 youyuanwu

I found this issue when searching for something else, but I think it is a good call out. I think this could be handled with a lifetime association.

dallasmarlow avatar Oct 31 '25 13:10 dallasmarlow