From 0230a7173f3f281cc2a9f86aecec7532eadef5ec Mon Sep 17 00:00:00 2001 From: Michael Paulson Date: Fri, 22 Jul 2016 11:11:56 -0700 Subject: [PATCH] feat(mutable-js): The mutable Scalar generation. This is just the initial commit to start the conversation on adding mutation to javascript. --- src/idl_gen_js.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/idl_gen_js.cpp b/src/idl_gen_js.cpp index d7c913e50..fec578029 100644 --- a/src/idl_gen_js.cpp +++ b/src/idl_gen_js.cpp @@ -79,7 +79,7 @@ class JsGenerator : public BaseGenerator { for (auto it = parser_.structs_.vec.begin(); it != parser_.structs_.vec.end(); ++it) { auto &struct_def = **it; - GenStruct(struct_def, decl_code_ptr, exports_code_ptr); + GenStruct(parser_, struct_def, decl_code_ptr, exports_code_ptr); } } void GenNamespaces(std::string *code_ptr, std::string *exports_ptr) { @@ -361,7 +361,7 @@ static void GenStructBody(const StructDef &struct_def, } // Generate an accessor struct with constructor for a flatbuffers struct. -void GenStruct(StructDef &struct_def, std::string *code_ptr, std::string *exports_ptr) { +void GenStruct(const Parser &parser, StructDef &struct_def, std::string *code_ptr, std::string *exports_ptr) { if (struct_def.generated) return; std::string &code = *code_ptr; std::string &exports = *exports_ptr; @@ -550,6 +550,22 @@ void GenStruct(StructDef &struct_def, std::string *code_ptr, std::string *export } code += "};\n\n"; + // Adds the mutable scalar value to the output + if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer) { + std::string annotations = "@param {" + GenTypeName(field.value.type, true) + "} value\n"; + GenDocComment(code_ptr, annotations + + "@returns {boolean}"); + + code += object_name + ".prototype.mutate_" + field.name + " = function(value) {\n"; + code += " var offset = this.bb.__offset(this.bb_pos, " + NumToString(field.value.offset) + ")\n\n"; + code += " if (offset === 0) {\n"; + code += " return false;\n"; + code += " }\n\n"; + code += " this.bb.write" + MakeCamel(GenType(field.value.type)) + "(this.bb_pos + offset, value);\n"; + code += " return true;\n"; + code += "}\n\n"; + } + // Emit vector helpers if (field.value.type.base_type == BASE_TYPE_VECTOR) { // Emit a length helper