From 0bb3ce69353d94f88da4658768fbac2934a035f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Harrtell?= Date: Thu, 16 May 2019 20:43:31 +0200 Subject: [JS/TS] Size prefix support (#5326) * WIP size prefix support * Consider size prefix in overloaded variant * Work on code gen * Disabled helper functions in code gen * Enabled helper functions in code gen * Fix size prefixed test * Fix bad function call * Add SIZE_PREFIX_LENGTH * Fix review comments --- js/flatbuffers.js | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) (limited to 'js') diff --git a/js/flatbuffers.js b/js/flatbuffers.js index 41608520..461cd7af 100644 --- a/js/flatbuffers.js +++ b/js/flatbuffers.js @@ -48,6 +48,12 @@ flatbuffers.SIZEOF_INT = 4; */ flatbuffers.FILE_IDENTIFIER_LENGTH = 4; +/** + * @type {number} + * @const + */ +flatbuffers.SIZE_PREFIX_LENGTH = 4; + /** * @enum {number} */ @@ -676,12 +682,14 @@ outer_loop: * * @param {flatbuffers.Offset} root_table * @param {string=} opt_file_identifier + * @param {boolean=} opt_size_prefix */ -flatbuffers.Builder.prototype.finish = function(root_table, opt_file_identifier) { +flatbuffers.Builder.prototype.finish = function(root_table, opt_file_identifier, opt_size_prefix) { + var size_prefix = opt_size_prefix ? flatbuffers.SIZE_PREFIX_LENGTH : 0; if (opt_file_identifier) { var file_identifier = opt_file_identifier; this.prep(this.minalign, flatbuffers.SIZEOF_INT + - flatbuffers.FILE_IDENTIFIER_LENGTH); + flatbuffers.FILE_IDENTIFIER_LENGTH + size_prefix); if (file_identifier.length != flatbuffers.FILE_IDENTIFIER_LENGTH) { throw new Error('FlatBuffers: file identifier must be length ' + flatbuffers.FILE_IDENTIFIER_LENGTH); @@ -690,11 +698,24 @@ flatbuffers.Builder.prototype.finish = function(root_table, opt_file_identifier) this.writeInt8(file_identifier.charCodeAt(i)); } } - this.prep(this.minalign, flatbuffers.SIZEOF_INT); + this.prep(this.minalign, flatbuffers.SIZEOF_INT + size_prefix); this.addOffset(root_table); + if (size_prefix) { + this.addInt32(this.bb.capacity() - this.space); + } this.bb.setPosition(this.space); }; +/** + * Finalize a size prefixed buffer, pointing to the given `root_table`. + * + * @param {flatbuffers.Offset} root_table + * @param {string=} opt_file_identifier + */ +flatbuffers.Builder.prototype.finishSizePrefixed = function (root_table, opt_file_identifier) { + this.finish(root_table, opt_file_identifier, true); +}; + /// @cond FLATBUFFERS_INTERNAL /** * This checks a required field has been set in a given table that has -- cgit v1.2.3