[Rust] idl_gen_rust.cpp: (Option/required-aware codegen for unions) (#5850)
authorjrop <jrapodaca@gmail.com>
Mon, 4 May 2020 07:16:57 +0000 (01:16 -0600)
committerGitHub <noreply@github.com>
Mon, 4 May 2020 07:16:57 +0000 (00:16 -0700)
* idl_gen_rust.cpp: Fix google/flatbuffers#5849 (Option/required-aware
codegen for unions)

The generated code was assuming that an Option is always returned by the
union-getter method: however, this is only true if the field is not
marked as `(required)`.

* idl_gen_rust.cpp: flip conditional

* idl_gen_rust.cpp: Add comment, as requested in review

The code added is not covered by the integration test

src/idl_gen_rust.cpp

index 55b8439..cece221 100644 (file)
@@ -1350,9 +1350,17 @@ class RustGenerator : public BaseGenerator {
         code_ +=
             "    if self.{{FIELD_TYPE_FIELD_NAME}}_type() == "
             "{{U_ELEMENT_ENUM_TYPE}} {";
-        code_ +=
+
+        // The following logic is not tested in the integration test,
+        // as of April 10, 2020
+        if (field.required) {
+          code_ += "      let u = self.{{FIELD_NAME}}();";
+          code_ += "      Some({{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
+        } else {
+          code_ +=
             "      self.{{FIELD_NAME}}().map(|u| "
             "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
+        }
         code_ += "    } else {";
         code_ += "      None";
         code_ += "    }";