Skip to content

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

@youyuanwu

Description

@youyuanwu

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions