Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion src/idl_gen_rust.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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}} {";
Expand Down
4 changes: 4 additions & 0 deletions tests/arrays_test.fbs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ struct ArrayStruct{
f:[int64:2];
}

struct LargeArrayStruct {
d:[ubyte:64];
}

table ArrayTable{
a:ArrayStruct;
}
Expand Down