From a4249df995661d184cfd051e42d619101af528e8 Mon Sep 17 00:00:00 2001 From: RenzoMXD <170978465+RenzoMXD@users.noreply.github.com> Date: Tue, 3 Mar 2026 16:06:25 +0000 Subject: [PATCH] fix(flatbuffers): use manual impl Default for struct object types --- src/idl_gen_rust.cpp | 37 ++++++++++++++++++++++++++++++++++++- tests/arrays_test.fbs | 4 ++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp index b7a565d00cd..528d5d92c20 100644 --- a/src/idl_gen_rust.cpp +++ b/src/idl_gen_rust.cpp @@ -2939,13 +2939,48 @@ class RustGenerator : public BaseGenerator { // Generate Struct Object. if (parser_.opts.generate_object_based_api) { // Struct declaration - code_ += "#[derive(Debug, Clone, PartialEq, Default)]"; + code_ += "#[derive(Debug, Clone, PartialEq)]"; code_ += "{{ACCESS_TYPE}} struct {{STRUCT_OTY}} {"; ForAllStructFields(struct_def, [&](const FieldDef& field) { (void)field; // unused. code_ += "pub {{FIELD}}: {{FIELD_OTY}},"; }); code_ += "}"; + // Manual impl Default to avoid issues with arrays > 32 elements + // where #[derive(Default)] fails on older Rust versions. + code_ += "impl Default for {{STRUCT_OTY}} {"; + code_ += " fn default() -> Self {"; + code_ += " Self {"; + ForAllStructFields(struct_def, [&](const FieldDef& field) { + const auto full_type = GetFullType(field.value.type); + switch (full_type) { + case ftArrayOfBuiltin: { + // e.g. [0; 64] for [u8; 64] + code_ += " {{FIELD}}: [0; " + + NumToString(field.value.type.fixed_length) + "],"; + break; + } + case ftArrayOfEnum: + case ftArrayOfStruct: { + // e.g. Default::default() works for arrays of structs/enums + // since their size is bounded by the schema, but use + // array_init for safety with large arrays. + code_ += + " {{FIELD}}: ::flatbuffers::array_init(|_| " + "Default::default()),"; + break; + } + default: { + std::string default_value = + GetDefaultValue(field, kObject); + code_ += " {{FIELD}}: " + default_value + ","; + break; + } + } + }); + code_ += " }"; + code_ += " }"; + code_ += "}"; // The `pack` method that turns the native struct into its Flatbuffers // counterpart. code_ += "impl {{STRUCT_OTY}} {"; diff --git a/tests/arrays_test.fbs b/tests/arrays_test.fbs index 90cb0d7267c..e914805bf40 100644 --- a/tests/arrays_test.fbs +++ b/tests/arrays_test.fbs @@ -18,6 +18,10 @@ struct ArrayStruct{ f:[int64:2]; } +struct LargeArrayStruct { + d:[ubyte:64]; +} + table ArrayTable{ a:ArrayStruct; }